-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraphql.ts
89 lines (81 loc) · 2.24 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
87
88
89
import { createSchema, createYoga } from 'graphql-yoga'
import { useGraphQLSSE } from '@graphql-yoga/plugin-graphql-sse'
import { useDeferStream } from '@graphql-yoga/plugin-defer-stream'
import { useResponseCache } from '@graphql-yoga/plugin-response-cache'
import { cacheControlDirective } from '@graphql-yoga/plugin-response-cache'
import { useImmediateIntrospection } from '@envelop/immediate-introspection'
const typeDefs = /* graphql */ `
# the directive needs to be defined in the schema
${cacheControlDirective}
type Query {
health: String
slow: String @cacheControl(maxAge: 3600000) # cache for 1 hour
}
type Subscription {
countdown(from: Int!): Int!
}
`
const schema = createSchema({
typeDefs: () => typeDefs,
resolvers: {
Query: {
health: () => `OK`,
/**
* simulate a slow query
* running this for the first time will take 5 seconds
* subsequent requests will be instant, served from the cache
*
* cache is set with the `useResponseCache` plugin
*/
slow: async () => {
await new Promise(resolve => setTimeout(resolve, 4_500))
return "I'm slow"
}
},
Subscription: {
countdown: {
subscribe: async function* (_, { from }) {
for (let index = from; index >= 0; index--) {
await new Promise(resolve => setTimeout(resolve, 750)) // 0.75 seconds
yield { countdown: index }
}
}
}
}
}
})
const defaultQuery = /* graphql */ `
# run this to see a subscription stream example
subscription StreamExample {
countdown(from: 12)
}
# the first time you run this it'll be slow
# run it again to see the cache in action
query QueryCachingExample {
slow
}
#
# click the play button and it'll let you choose what to run
#`.trim()
export const yoga = createYoga({
schema,
graphqlEndpoint: '/graphql',
graphiql: {
defaultQuery,
disableTabs: true,
title: 'workers-graphql',
defaultEditorToolsVisibility: false
},
/**
* more plugins here https://the-guild.dev/graphql/envelop/plugins
*/
plugins: [
useResponseCache({
enabled: _ => true,
session: _ => null
}),
useDeferStream(),
useGraphQLSSE(),
useImmediateIntrospection()
]
})