forked from contra/graphql-helix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
123 lines (103 loc) · 2.83 KB
/
server.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
import express from "express";
import { ExecutionResult, GraphQLError } from "graphql";
import {
getGraphQLParameters,
processRequest,
renderGraphiQL,
shouldRenderGraphiQL,
} from "graphql-helix";
import { schema } from "./schema";
const formatResult = (result: ExecutionResult) => {
const formattedResult: ExecutionResult = {
data: result.data,
};
if (result.errors) {
formattedResult.errors = result.errors.map((error) => {
// Log the error using the logger of your choice
console.log(error);
// Return a generic error message instead
return new GraphQLError(
"Sorry, something went wrong",
error.nodes,
error.source,
error.positions,
error.path,
null,
{
// Adding some metadata to the error
timestamp: Date.now(),
}
);
});
}
return formattedResult;
};
const app = express();
app.use(express.json());
app.use("/graphql", async (req, res) => {
const request = {
body: req.body,
headers: req.headers,
method: req.method,
query: req.query,
};
if (shouldRenderGraphiQL(request)) {
res.send(renderGraphiQL());
} else {
const { operationName, query, variables } = getGraphQLParameters(request);
const result = await processRequest({
operationName,
query,
variables,
request,
schema,
});
if (result.type === "RESPONSE") {
result.headers.forEach(({ name, value }) => res.setHeader(name, value));
res.status(result.status);
res.json(formatResult(result.payload));
} else if (result.type === "MULTIPART_RESPONSE") {
res.writeHead(200, {
Connection: "keep-alive",
"Content-Type": 'multipart/mixed; boundary="-"',
"Transfer-Encoding": "chunked",
});
req.on("close", () => {
result.unsubscribe();
});
res.write("---");
await result.subscribe((result) => {
const chunk = Buffer.from(JSON.stringify(result), "utf8");
const data = [
"",
"Content-Type: application/json; charset=utf-8",
"Content-Length: " + String(chunk.length),
"",
chunk,
];
if (result.hasNext) {
data.push("---");
}
res.write(data.join("\r\n"));
});
res.write("\r\n-----\r\n");
res.end();
} else {
res.writeHead(200, {
"Content-Type": "text/event-stream",
Connection: "keep-alive",
"Cache-Control": "no-cache",
});
req.on("close", () => {
result.unsubscribe();
});
await result.subscribe((result) => {
res.write(`data: ${JSON.stringify(formatResult(result))}\n\n`);
});
}
}
});
const port = process.env.PORT || 4000;
app.listen(port, () => {
console.log(`GraphQL server is running on port ${port}.`);
});