aboutsummaryrefslogtreecommitdiff
path: root/src/index.js
diff options
context:
space:
mode:
authorFuwn <[email protected]>2022-03-20 01:28:42 -0700
committerFuwn <[email protected]>2022-03-20 01:28:42 -0700
commit03f2c8e35ba70c9d9496fd5ad5403520f7ebdc53 (patch)
tree568e508aff6db6325719abcb2c601520264c5de4 /src/index.js
downloadgraphql-api-03f2c8e35ba70c9d9496fd5ad5403520f7ebdc53.tar.xz
graphql-api-03f2c8e35ba70c9d9496fd5ad5403520f7ebdc53.zip
feat: 0.1.0 :star:
Diffstat (limited to 'src/index.js')
-rw-r--r--src/index.js56
1 files changed, 56 insertions, 0 deletions
diff --git a/src/index.js b/src/index.js
new file mode 100644
index 0000000..7419cc8
--- /dev/null
+++ b/src/index.js
@@ -0,0 +1,56 @@
+const apollo = require("./handlers/apollo");
+const playground = require("./handlers/playground");
+const setCors = require("./utils/setCors");
+
+const graphQLOptions = {
+ baseEndpoint: "/",
+ playgroundEndpoint: "/playground",
+ forwardUnmatchedRequestsToOrigin: false,
+ debug: false,
+
+ // cors: {
+ // allowCredentials: 'true',
+ // allowHeaders: 'Content-type',
+ // allowOrigin: '*',
+ // allowMethods: 'GET, POST, PUT',
+ // },
+ cors: true,
+
+ kvCache: true,
+};
+
+const handleRequest = async (request) => {
+ const url = new URL(request.url);
+
+ try {
+ if (url.pathname === graphQLOptions.baseEndpoint) {
+ const response =
+ request.method === "OPTIONS"
+ ? new Response("", { status: 204 })
+ : await apollo(request, graphQLOptions);
+
+ if (graphQLOptions.cors) {
+ setCors(response, graphQLOptions.cors);
+ }
+
+ return response;
+ } else if (
+ graphQLOptions.playgroundEndpoint &&
+ url.pathname === graphQLOptions.playgroundEndpoint
+ ) {
+ return playground(request, graphQLOptions);
+ } else if (graphQLOptions.forwardUnmatchedRequestsToOrigin) {
+ return fetch(request);
+ } else {
+ return new Response("Not found", { status: 404 });
+ }
+ } catch (err) {
+ return new Response(graphQLOptions.debug ? err : "Something went wrong", {
+ status: 500,
+ });
+ }
+};
+
+addEventListener("fetch", (event) => {
+ event.respondWith(handleRequest(event.request));
+});