2016-06-12 22:41:46 -07:00
|
|
|
import * as express from 'express';
|
|
|
|
import * as graphql from 'graphql';
|
2016-06-14 12:03:53 -07:00
|
|
|
import { runQuery } from '../core/runQuery';
|
2016-06-12 22:41:46 -07:00
|
|
|
|
|
|
|
export interface ExpressBindings {
|
|
|
|
schema: graphql.GraphQLSchema;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default function(options: ExpressBindings) {
|
|
|
|
if (!options) {
|
|
|
|
throw new Error('GraphQL middleware requires options.');
|
|
|
|
}
|
2016-06-14 12:03:53 -07:00
|
|
|
|
2016-06-12 22:41:46 -07:00
|
|
|
if (arguments.length > 1) {
|
|
|
|
throw new Error(`apolloServer expects exactly one argument, got ${arguments.length + 1}`);
|
|
|
|
}
|
2016-06-14 12:03:53 -07:00
|
|
|
|
2016-06-12 22:41:46 -07:00
|
|
|
return (req: express.Request, res: express.Response, next) => {
|
2016-06-14 12:03:53 -07:00
|
|
|
runQuery({
|
|
|
|
schema: options.schema,
|
|
|
|
query: req.body,
|
|
|
|
}).then(gqlResponse => {
|
|
|
|
res.set('Content-Type', 'application/json');
|
|
|
|
res.send({ data: gqlResponse.data });
|
|
|
|
}).catch(gqlResponse => {
|
|
|
|
res.send(gqlResponse.errorCode, { errors: gqlResponse.errors });
|
|
|
|
});
|
|
|
|
};
|
2016-06-12 22:41:46 -07:00
|
|
|
}
|