-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathhttp.ts
79 lines (76 loc) · 2.2 KB
/
http.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
import type { IncomingMessage, ServerResponse } from 'http';
import {
createHandler as createRawHandler,
HandlerOptions as RawHandlerOptions,
OperationContext,
} from '../handler';
/**
* The context in the request for the handler.
*
* @category Server/http
*/
export interface RequestContext {
res: ServerResponse;
}
/**
* Handler options when using the http adapter.
*
* @category Server/http
*/
export type HandlerOptions<Context extends OperationContext = undefined> =
RawHandlerOptions<IncomingMessage, RequestContext, Context>;
/**
* Create a GraphQL over HTTP spec compliant request handler for
* the Node environment http module.
*
* ```js
* import http from 'http';
* import { createHandler } from 'graphql-http/lib/use/http';
* import { schema } from './my-graphql-schema';
*
* const server = http.createServer(createHandler({ schema }));
*
* server.listen(4000);
* console.log('Listening to port 4000');
* ```
*
* @category Server/http
*/
export function createHandler<Context extends OperationContext = undefined>(
options: HandlerOptions<Context>,
): (req: IncomingMessage, res: ServerResponse) => Promise<void> {
const handle = createRawHandler(options);
return async function requestListener(req, res) {
try {
if (!req.url) {
throw new Error('Missing request URL');
}
if (!req.method) {
throw new Error('Missing request method');
}
const [body, init] = await handle({
url: req.url,
method: req.method,
headers: req.headers,
body: () =>
new Promise<string>((resolve) => {
let body = '';
req.on('data', (chunk) => (body += chunk));
req.on('end', () => resolve(body));
}),
raw: req,
context: { res },
});
res.writeHead(init.status, init.statusText, init.headers).end(body);
} catch (err) {
// The handler shouldnt throw errors.
// If you wish to handle them differently, consider implementing your own request handler.
console.error(
'Internal error occurred during request handling. ' +
'Please check your implementation.',
err,
);
res.writeHead(500).end();
}
};
}