-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.ts
215 lines (189 loc) · 5.55 KB
/
handler.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import {
DocumentNode,
execute,
ExecutionArgs,
getOperationAST,
GraphQLError,
OperationTypeNode,
parse,
Status,
subscribe,
tryCatchSync,
validate,
validateSchema,
} from "./deps.ts";
import { isAsyncGenerator, isRequestError, MessengerImpl } from "./utils.ts";
import {
CloseCode,
GRAPHQL_TRANSPORT_WS_PROTOCOL,
MessageType,
} from "./constants.ts";
import { GraphQLExecutionArgs } from "./types.ts";
import { validateWebSocketRequest } from "./validates.ts";
import { parseMessage } from "./parse.ts";
/** Create `Request` handler compliant GraphQL over WebSocket server.
* @throws `AggregateError` - When GraphQL schema validation error has occurred.
* ```ts
* import { createHandler } from "https://deno.land/x/graphql_websocket@$VERSION/mod.ts";
* import { serve } from "https://deno.land/std@$VERSION/http/mod.ts";
* import { buildSchema } from "https://esm.sh/graphql@$VERSION";
*
* const handler = createHandler({
* schema: buildSchema(`type Query { hello: String }
* type Subscription {
* greetings: String!
* }`),
* rootValue: {
* greetings: async function* () {
* for (const hi of ["Hi", "Bonjour", "Hola", "Ciao", "Zdravo"]) {
* yield { greetings: hi };
* }
* },
* },
* });
*
* serve(handler);
* ```
*/
export default function createHandler(
params: GraphQLExecutionArgs,
): (req: Request) => Response {
const validationResult = validateSchema(params.schema);
if (validationResult.length) {
throw new AggregateError(
validationResult,
"GraphQL schema validation error",
);
}
return (req: Request): Response => {
const [result, error] = validateWebSocketRequest(req);
if (!result) {
const headers = error.status === Status.MethodNotAllowed
? new Headers({ "Allow": "GET" })
: undefined;
return new Response(error.message, {
status: error.status,
headers,
});
}
const protocol = req.headers.get("sec-websocket-protocol") ?? undefined;
const [data, err] = tryCatchSync(() =>
Deno.upgradeWebSocket(req, { protocol })
);
if (!data) {
const msg = resolveErrorMsg(err);
return new Response(msg, {
status: Status.InternalServerError,
});
}
register(data.socket, params);
return data.response;
};
}
function register(
socket: WebSocket,
args: GraphQLExecutionArgs,
): void {
socket.addEventListener("open", () => {
if (socket.protocol !== GRAPHQL_TRANSPORT_WS_PROTOCOL) {
return socket.close(
CloseCode.SubprotocolNotAcceptable,
"Sub protocol is not acceptable",
);
}
}, {
once: true,
});
socket.addEventListener("message", async ({ data }) => {
const [message, error] = parseMessage(data);
if (!message) {
return socket.close(
CloseCode.BadRequest,
`Invalid message received. ${error.message}`,
);
}
const messenger = new MessengerImpl();
switch (message.type) {
case MessageType.ConnectionInit: {
safeSend(
socket,
JSON.stringify({
type: MessageType.ConnectionAck,
}),
);
break;
}
case MessageType.Ping: {
safeSend(
socket,
JSON.stringify({
type: MessageType.Pong,
}),
);
break;
}
case MessageType.Subscribe: {
const { payload } = message;
const [document, error] = tryCatchSync<DocumentNode, GraphQLError>(() =>
parse(payload.query)
);
if (!document) {
const msg = messenger.errorMsg(message.id, [error]);
return safeSend(socket, JSON.stringify(msg));
}
const validationResult = validate(args.schema, document);
if (validationResult.length) {
const msg = messenger.errorMsg(message.id, validationResult);
return safeSend(socket, JSON.stringify(msg));
}
const operationAST = getOperationAST(document);
if (!operationAST) {
const msg = messenger.errorMsg(message.id, [
new GraphQLError("Unable to identify operation"),
]);
return safeSend(socket, JSON.stringify(msg));
}
const executor = getExecutor(operationAST.operation);
const executionArgs: ExecutionArgs = {
...args,
document,
...payload,
};
const executionResult = await executor(executionArgs);
if (isAsyncGenerator(executionResult)) {
for await (const result of executionResult) {
const msg = messenger.nextMsg(message.id, result);
safeSend(socket, JSON.stringify(msg));
}
} else {
const msg = isRequestError(executionResult)
? messenger.errorMsg(message.id, executionResult.errors)
: messenger.nextMsg(message.id, executionResult);
safeSend(socket, JSON.stringify(msg));
}
const msg = messenger.completeMsg(message.id);
return safeSend(socket, JSON.stringify(msg));
}
}
});
}
function safeSend(
socket: WebSocket,
data: string | ArrayBufferLike | Blob | ArrayBufferView,
) {
if (socket.readyState === socket.OPEN) {
try {
socket.send(data);
} catch {
// noop
}
}
}
function getExecutor(
operationTypeNode: OperationTypeNode,
): typeof subscribe | typeof execute {
return operationTypeNode === "subscription" ? subscribe : execute;
}
function resolveErrorMsg(value: unknown): string {
return value instanceof Error ? value.message : "Unknown error has occurred.";
}