forked from reconbot/graphql-lambda-subscriptions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraphql-ws-schema.ts
113 lines (101 loc) · 2.64 KB
/
graphql-ws-schema.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/* eslint-disable @typescript-eslint/no-explicit-any */
import ws from 'ws'
import { useServer } from 'graphql-ws/lib/use/ws'
import { makeExecutableSchema } from '@graphql-tools/schema'
import { GraphQLError } from 'graphql'
const PORT = 4000
const typeDefs = `
type Query {
hello: String
dontResolve: String
}
type Subscription {
greetings: String
onSubscribeError: String
onResolveError: String
oneEvent: String
}
`
const resolvers = {
Query: {
hello: () => 'Hello World!',
// eslint-disable-next-line @typescript-eslint/no-empty-function
dontResolve: () => new Promise(() => {}),
},
Subscription: {
greetings:{
subscribe: async function*(){
yield { greetings: 'yoyo' }
yield { greetings: 'hows it' }
yield { greetings: 'howdy' }
},
},
onSubscribeError: {
// eslint-disable-next-line require-yield
subscribe: async function*() {
throw new Error('onSubscribeError')
},
},
onResolveError: {
subscribe: async function*(){
yield { greetings: 'yoyo' }
},
resolve() {
throw new Error('resolver error')
},
},
oneEvent:{
subscribe: async function*(){
yield { oneEvent: 'lets start!' }
// eslint-disable-next-line @typescript-eslint/no-empty-function
await new Promise(() => {})
},
},
},
}
const schema = makeExecutableSchema({
typeDefs,
resolvers,
})
export const startGqlWSServer = async (): Promise<{
url: string
stop: () => Promise<void>
}> => {
const server = new ws.Server({
port: PORT,
path: '/',
})
server.on('connection', connection => {
// connection.on('message', msg => console.log({ msg: msg.toString() }))
const send = connection.send
connection.send = (data: any, cb: any) => {
// console.log({ send: data })
return send.call(connection, data, cb)
}
const close = connection.close
connection.close = (code?: number | undefined, data?: string | undefined) => {
// console.log({ close: { code, data: data?.toString() } })
return close.call(connection, code, data)
}
})
useServer(
{
schema,
async onSubscribe(ctx, message) {
if (message?.payload?.query === 'subscription { onSubscribeError }') {
return [
new GraphQLError('onSubscribeError'),
]
}
},
},
server,
)
await new Promise(resolve => server.on('listening', resolve))
// console.log('server started')
const stop = () => new Promise<void>(resolve => server.close(() => resolve()))
return {
url: `ws://localhost:${PORT}`,
stop,
}
}