/
koaApollo.ts
65 lines (57 loc) 路 1.64 KB
/
koaApollo.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
import Koa from 'koa';
import {
GraphQLOptions,
ServerOptionsFunction,
HttpQueryError,
runHttpQuery,
convertNodeHttpToRequest,
} from 'apollo-server-core';
export type KoaGraphQLOptionsFunction = ServerOptionsFunction<[Koa.Context]>;
export interface KoaHandler {
(ctx: Koa.Context, next): void;
}
export function graphqlKoa(
options: GraphQLOptions | KoaGraphQLOptionsFunction,
): KoaHandler {
if (!options) {
throw new Error('Apollo Server requires options.');
}
if (arguments.length > 1) {
// TODO: test this
throw new Error(
`Apollo Server expects exactly one argument, got ${arguments.length}`,
);
}
const graphqlHandler = (ctx: Koa.Context): Promise<void> => {
return runHttpQuery([ctx], {
method: ctx.request.method,
options: options,
query:
ctx.request.method === 'POST'
? // fallback to ctx.req.body for koa-multer support
ctx.request.body || (ctx.req as any).body
: ctx.request.query,
request: convertNodeHttpToRequest(ctx.req),
}).then(
({ graphqlResponse, responseInit }) => {
Object.keys(responseInit.headers).forEach(key =>
ctx.set(key, responseInit.headers[key]),
);
ctx.body = graphqlResponse;
},
(error: HttpQueryError) => {
if ('HttpQueryError' !== error.name) {
throw error;
}
if (error.headers) {
Object.keys(error.headers).forEach(header => {
ctx.set(header, error.headers[header]);
});
}
ctx.status = error.statusCode;
ctx.body = error.message;
},
);
};
return graphqlHandler;
}