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

140 lines
3.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, formatApolloErrors } from 'apollo-server-core';
2018-05-01 06:09:48 -07:00
import * as accepts from 'accepts';
import { graphqlExpress } from './expressApollo';
import {
processRequest as processFileUploads,
GraphQLUpload,
} from 'apollo-upload-server';
const gql = String.raw;
2018-05-01 06:09:48 -07:00
export interface ServerRegistration {
app: express.Application;
server: ApolloServerBase<express.Request>;
path?: string;
cors?: corsMiddleware.CorsOptions;
bodyParserConfig?: OptionsJson;
onHealthCheck?: (req: express.Request) => Promise<any>;
disableHealthCheck?: boolean;
//https://github.com/jaydenseric/apollo-upload-server#options
uploads?: boolean | Record<string, any>;
2018-05-01 06:09:48 -07:00
}
const fileUploadMiddleware = (
uploadsConfig: Record<string, any>,
server: ApolloServerBase<express.Request>,
) => (
req: express.Request,
res: express.Response,
next: express.NextFunction,
) => {
if (req.is('multipart/form-data')) {
processFileUploads(req, uploadsConfig)
.then(body => {
req.body = body;
next();
})
.catch(error => {
if (error.status && error.expose) res.status(error.status);
next(
formatApolloErrors([error], {
formatter: server.requestOptions.formatError,
debug: server.requestOptions.debug,
logFunction: server.requestOptions.logFunction,
}),
);
});
} else {
next();
}
};
2018-05-01 06:09:48 -07:00
export const registerServer = async ({
app,
server,
path,
cors,
bodyParserConfig,
disableHealthCheck,
onHealthCheck,
uploads,
2018-05-01 06:09:48 -07:00
}: ServerRegistration) => {
2018-05-01 11:05:26 -07:00
if (!path) path = '/graphql';
if (!disableHealthCheck) {
//uses same path as engine
app.use('/.well-known/apollo/server-health', (req, res, next) => {
//Response follows https://tools.ietf.org/html/draft-inadarei-api-health-check-01
res.type('application/health+json');
if (onHealthCheck) {
onHealthCheck(req)
.then(() => {
res.json({ status: 'pass' });
})
.catch(() => {
res.status(503).json({ status: 'fail' });
});
} else {
res.json({ status: 'pass' });
}
});
}
let uploadsMiddleware;
if (uploads !== false) {
server.enhanceSchema({
typeDefs: gql`
scalar Upload
`,
resolvers: { Upload: GraphQLUpload },
});
uploadsMiddleware = fileUploadMiddleware(
typeof uploads !== 'boolean' ? uploads : {},
server,
);
}
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),
uploadsMiddleware,
(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.subscriptionsPath,
})(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
};