-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
graphql.ts
86 lines (77 loc) · 2.39 KB
/
graphql.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
84
85
86
import type { Handle } from '@sveltejs/kit'
import { createSchema, createYoga, type Plugin, type YogaInitialContext } from 'graphql-yoga'
// export type KitQLServerOptions<TServerContext, TUserContext> = Omit<
// YogaServerOptions<TServerContext, TUserContext>,
// 'graphiql'
// >
export type GraphQLKitQL<TUserContext> = {
/**
* If you set the `graphiQLPath`, on a GET request you will be redirected there
* If not, you will get a 404 (security by default ;))))))))))))))))))
*/
graphiQLPath?: string
/**
* defaults to /graphql
*/
endpoint?: string
context?:
| ((initialContext: YogaInitialContext) => Promise<TUserContext> | TUserContext)
| Promise<TUserContext>
| TUserContext
plugins?: Plugin[]
}
export function handleGraphql<TUserContext>(options?: GraphQLKitQL<TUserContext>): Handle {
// set defaults
const { graphiQLPath, endpoint, plugins, context } = {
graphiQLPath: undefined,
endpoint: '/graphql',
plugins: [],
context: () => {
return {} as TUserContext
},
...options,
}
if (!endpoint.startsWith('/')) {
throw new Error("graphql endpoint must start with '/'")
}
if (graphiQLPath && !graphiQLPath.startsWith('/')) {
throw new Error("graphiQLPath path must start with '/'")
}
const kitqlServer = createYoga<YogaInitialContext, TUserContext>({
logging: true,
schema: createSchema({
typeDefs: `
type Query {
is_it_working: String
}
`,
resolvers: {
Query: {
is_it_working: () =>
'Yes yoga is up and running! Now, to make it work with your own schema, you need to send kitQLModules(modules) via plugins',
},
},
}),
context,
plugins,
graphqlEndpoint: endpoint,
fetchAPI: globalThis,
})
return async ({ event, resolve }) => {
if (event.url && event.url.pathname === endpoint) {
if (event.request.method === 'GET') {
// If we know graphiQLPath, let's go there
if (graphiQLPath) {
return new Response('Redirect', { status: 303, headers: { Location: graphiQLPath } })
}
// if not, let's bring the 404!
return new Response(`${endpoint} Not found`, { status: 404 })
}
if (event.request.method === 'POST') {
return kitqlServer.handleRequest(event.request, null)
}
}
// Fallback to normal request
return resolve(event)
}
}