-
Notifications
You must be signed in to change notification settings - Fork 2k
/
microApollo.ts
74 lines (64 loc) 路 2.04 KB
/
microApollo.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
import {
GraphQLOptions,
runHttpQuery,
convertNodeHttpToRequest,
} from 'apollo-server-core';
import { send, json, RequestHandler } from 'micro';
import * as url from 'url';
import { IncomingMessage, ServerResponse } from 'http';
import { MicroRequest } from './types';
// Allowed Micro Apollo Server options.
export interface MicroGraphQLOptionsFunction {
(req?: IncomingMessage): GraphQLOptions | Promise<GraphQLOptions>;
}
// Utility function used to set multiple headers on a response object.
function setHeaders(res: ServerResponse, headers: Object): void {
Object.keys(headers).forEach((header: string) => {
res.setHeader(header, headers[header]);
});
}
// Build and return an async function that passes incoming GraphQL requests
// over to Apollo Server for processing, then fires the results/response back
// using Micro's `send` functionality.
export function graphqlMicro(
options: GraphQLOptions | MicroGraphQLOptionsFunction,
): RequestHandler {
if (!options) {
throw new Error('Apollo Server requires options.');
}
if (arguments.length > 1) {
throw new Error(
`Apollo Server expects exactly one argument, got ${arguments.length}`,
);
}
const graphqlHandler = async (req: MicroRequest, res: ServerResponse) => {
let query;
try {
query =
req.method === 'POST'
? req.filePayload || (await json(req))
: url.parse(req.url, true).query;
} catch (error) {
// Do nothing; `query` stays `undefined`
}
try {
const { graphqlResponse, responseInit } = await runHttpQuery([req, res], {
method: req.method,
options,
query,
request: convertNodeHttpToRequest(req),
});
setHeaders(res, responseInit.headers);
return graphqlResponse;
} catch (error) {
if ('HttpQueryError' === error.name && error.headers) {
setHeaders(res, error.headers);
}
if (!error.statusCode) {
error.statusCode = 500;
}
send(res, error.statusCode, error.message);
}
};
return graphqlHandler;
}