-
Notifications
You must be signed in to change notification settings - Fork 2
/
api.mjs
96 lines (85 loc) · 1.81 KB
/
api.mjs
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
90
91
92
93
94
95
96
import { useServer } from 'graphql-ws/lib/use/ws'
import { createYoga, createSchema } from 'graphql-yoga'
import { createServer } from 'node:http'
import { WebSocketServer } from 'ws'
import { resolvers, typeDefs } from './schema/index.mjs'
async function main() {
const yogaApp = createYoga({
schema: createSchema({
typeDefs,
resolvers,
}),
graphiql: {
// Use WebSockets in GraphiQL
subscriptionsProtocol: 'WS',
defaultQuery: `
query Items {
items{
totalCount
edges{
node{
id
text
}
}
}
}
mutation AddItem {
addItem(input:{text: "coucou"}) {
item {
id
}
}
}
subscription SubToNewItem {
newItem {
item {
id
text
}
}
}
`,
},
})
// Get NodeJS Server from Yoga
const httpServer = createServer(yogaApp)
// Create WebSocket server instance from our Node server
const wsServer = new WebSocketServer({
server: httpServer,
path: yogaApp.graphqlEndpoint,
})
// Integrate Yoga's Envelop instance and NodeJS server with graphql-ws
useServer(
{
execute: (args) => args.rootValue.execute(args),
subscribe: (args) => args.rootValue.subscribe(args),
onSubscribe: async (ctx, msg) => {
const { schema, execute, subscribe, contextFactory, parse, validate } =
yogaApp.getEnveloped(ctx)
const args = {
schema,
operationName: msg.payload.operationName,
document: parse(msg.payload.query),
variableValues: msg.payload.variables,
contextValue: await contextFactory(),
rootValue: {
execute,
subscribe,
},
}
const errors = validate(args.schema, args.document)
if (errors.length) return errors
return args
},
},
wsServer
)
httpServer.listen(4000, () => {
console.info('Server is running on http://localhost:4000/graphql')
})
}
main().catch((e) => {
console.error(e)
process.exit(1)
})