1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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));
});
|