apollo-server/packages/apollo-server-express/src/ApolloServer.ts

60 lines
1.6 KiB
TypeScript
Raw Normal View History

2018-05-01 06:09:48 -07:00
import * as express from 'express';
import * as corsMiddleware from 'cors';
import { json, OptionsJson } from 'body-parser';
2018-05-01 06:09:48 -07:00
import { createServer, Server as HttpServer } from 'http';
import gui from 'graphql-playground-middleware-express';
import { ApolloServerBase } from 'apollo-server-core';
import * as accepts from 'accepts';
import { graphqlExpress } from './expressApollo';
export interface ServerRegistration {
app: express.Application;
server: ApolloServerBase<express.Request>;
path?: string;
cors?: corsMiddleware.CorsOptions;
bodyParserConfig?: OptionsJson;
2018-05-01 06:09:48 -07:00
}
export const registerServer = async ({
app,
server,
path,
cors,
bodyParserConfig,
2018-05-01 06:09:48 -07:00
}: ServerRegistration) => {
2018-05-01 11:05:26 -07:00
if (!path) path = '/graphql';
2018-05-01 06:09:48 -07:00
// XXX multiple paths?
2018-05-01 11:05:26 -07:00
server.use({
path,
getHttp: () => createServer(app),
});
2018-05-01 06:09:48 -07:00
app.use(
path,
corsMiddleware(cors),
json(bodyParserConfig),
(req, res, next) => {
// make sure we check to see if graphql gui should be on
if (!server.disableTools && req.method === 'GET') {
//perform more expensive content-type check only if necessary
const accept = accepts(req);
const types = accept.types() as string[];
const prefersHTML =
types.find(
(x: string) => x === 'text/html' || x === 'application/json',
) === 'text/html';
2018-05-01 06:09:48 -07:00
if (prefersHTML) {
return gui({
endpoint: path,
subscriptionsEndpoint: server.subscriptionsEnabled && path,
})(req, res, next);
}
2018-05-01 06:09:48 -07:00
}
return graphqlExpress(server.request.bind(server))(req, res, next);
},
);
2018-05-01 06:09:48 -07:00
};