forked from fastify/benchmarks
-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathuWebSockets-graphql+jit.js
69 lines (63 loc) · 1.5 KB
/
uWebSockets-graphql+jit.js
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
"use strict";
const { parse } = require("graphql");
const { compileQuery } = require("graphql-jit");
const uws = require("uWebSockets.js");
const { createApolloSchema } = require("../lib/schemas/createApolloSchema");
const cache = {};
const schema = createApolloSchema();
uws
.App()
.post("/graphql", (res) => {
readJson(
res,
(body) => {
const { query } = body;
let compiled = cache[query];
if (!compiled) {
const document = parse(query);
compiled = cache[query] = compileQuery(schema, document);
}
const ans = compiled.query({}, {}, {});
res.end(JSON.stringify(ans));
},
() => {},
);
})
.listen(4001, () => {});
function readJson(res, cb, err) {
let buffer;
/* Register data cb */
res.onData((ab, isLast) => {
let chunk = Buffer.from(ab);
if (isLast) {
let json;
if (buffer) {
try {
json = JSON.parse(Buffer.concat([buffer, chunk]));
} catch (e) {
/* res.close calls onAborted */
res.close();
return;
}
cb(json);
} else {
try {
json = JSON.parse(chunk);
} catch (e) {
/* res.close calls onAborted */
res.close();
return;
}
cb(json);
}
} else {
if (buffer) {
buffer = Buffer.concat([buffer, chunk]);
} else {
buffer = Buffer.concat([chunk]);
}
}
});
/* Register error cb */
res.onAborted(err);
}