-
Notifications
You must be signed in to change notification settings - Fork 5
/
mod.ts
83 lines (78 loc) · 2.39 KB
/
mod.ts
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import {
GQLOptions,
runHttpQuery,
} from "https://deno.land/x/[email protected]/common.ts";
import { renderPlaygroundPage } from "https://deno.land/x/[email protected]/graphiql/render.ts";
import type { GQLRequest } from "https://deno.land/x/[email protected]/types.ts";
// !!! all code below is from https://deno.land/x/[email protected]/http.ts
// except for removal of dynamic import
/**
* Create a new GraphQL HTTP middleware with schema, context etc
* @param {GQLOptions} options
*
* @example
* ```ts
* const graphql = await GraphQLHTTP({ schema })
*
* for await (const req of s) graphql(req)
* ```
*/
export function GraphQLHTTP<
Req extends GQLRequest = GQLRequest,
Ctx extends { request: Req } = { request: Req }
>({ playgroundOptions = {}, headers = {}, ...options }: GQLOptions<Ctx, Req>) {
return async (request: Req) => {
if (options.graphiql && request.method === "GET") {
if (request.headers.get("Accept")?.includes("text/html")) {
// !!! only modified portion is here
// const { renderPlaygroundPage } = await import(
// "./graphiql/render.ts"
// );
// !!! end of modified portion
const playground = renderPlaygroundPage({
...playgroundOptions,
endpoint: "/graphql",
});
return new Response(playground, {
headers: new Headers({
"Content-Type": "text/html",
...headers,
}),
});
} else {
return new Response('"Accept" header value must include text/html', {
status: 400,
headers: new Headers(headers),
});
}
} else {
if (!["PUT", "POST", "PATCH"].includes(request.method)) {
return new Response("Method Not Allowed", {
status: 405,
headers: new Headers(headers),
});
} else {
try {
const result = await runHttpQuery<Req, Ctx>(
await request.json(),
options,
{ request }
);
return new Response(JSON.stringify(result, null, 2), {
status: 200,
headers: new Headers({
"Content-Type": "application/json",
...headers,
}),
});
} catch (e) {
console.error(e);
return new Response("Malformed request body", {
status: 400,
headers: new Headers(headers),
});
}
}
}
};
}