forked from apollographql/apollo-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkoaApollo.ts
47 lines (42 loc) · 1.14 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
import {
GraphQLSchema,
GraphQLResult,
} from 'graphql';
import { runQuery } from '../core/runQuery';
//import * as GraphiQL from '../modules/renderGraphiQL';
export interface KoaApolloOptions {
schema: GraphQLSchema;
formatError?: Function;
rootValue?: any;
context?: any;
logFunction?: Function;
}
export function koaApollo(options: KoaApolloOptions): GraphQLResult {
if (!options) {
throw new Error('Apollo koa middleware requires options.');
}
if (arguments.length > 1) {
throw new Error(`apolloServer expects exactly one argument, got ${arguments.length + 1}`);
}
return function *() {
try {
const query = getQueryString(this.request);
const gqlResponse = yield runQuery({
schema: options.schema,
query: query,
context: options.context || {},
});
this.body = gqlResponse;
} catch (e) {
this.body = { errors: [e.stack] };
}
};
}
function getQueryString(req) {
if (req.method === 'POST') {
return req.body.query;
} else if (req.method === 'GET') {
return req.query.query;
}
throw new Error(`HTTP method ${req.method} not supported`);
}