-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
graphiql.ts
63 lines (53 loc) · 1.66 KB
/
graphiql.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
import type { Handle } from '@sveltejs/kit'
import type { GraphiQLRendererOptions as GraphiQLYogaOptions } from 'graphql-yoga/typings/plugins/useGraphiQL'
export type GraphiQLKitQL = Omit<GraphiQLYogaOptions, 'headers' | 'endpoint'> & {
headers?: Record<string, string>
enabled?: boolean
endpoint?: string
/**
* This is the graphiQLPath in the SvelteKit app
* @default is '/graphiql'
*/
graphiQLPath?: string
}
async function getGraphiQLBody(graphiqlOptions: GraphiQLYogaOptions) {
try {
// @ts-ignore
const { renderGraphiQL: renderGraphiQLOffline } = await import('@graphql-yoga/render-graphiql')
return renderGraphiQLOffline(graphiqlOptions)
} catch (e: any) {
// user did not add it as a dependency
const { renderGraphiQL: renderGraphiQLOnline } = await import('graphql-yoga')
return renderGraphiQLOnline(graphiqlOptions)
}
}
export function handleGraphiql(options?: GraphiQLKitQL): Handle {
const { graphiQLPath, headers, enabled, ...opts } = {
title: 'KitQL',
endpoint: '/graphql',
graphiQLPath: '/graphiql',
enabled: true,
...options,
}
if (!graphiQLPath.startsWith('/')) {
throw new Error("graphiql graphiQLPath must start with '/'")
}
const bodyPromise = enabled
? getGraphiQLBody({
...opts,
headers: JSON.stringify(headers ?? {}),
})
: ''
return async ({ event, resolve }) => {
if (enabled && event.url && event.url.pathname === graphiQLPath) {
return new Response(await bodyPromise, {
status: 200,
headers: {
'Content-Type': 'text/html',
},
})
}
// Fallback to normal request
return resolve(event)
}
}