-
Notifications
You must be signed in to change notification settings - Fork 2k
/
ApolloServer.ts
143 lines (129 loc) · 3.68 KB
/
ApolloServer.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import * as express from 'express';
import * as corsMiddleware from 'cors';
import { json, OptionsJson } from 'body-parser';
import { createServer, Server as HttpServer } from 'http';
import gui from 'graphql-playground-middleware-express';
import { ApolloServerBase, formatApolloErrors } from 'apollo-server-core';
import * as accepts from 'accepts';
import { graphqlExpress } from './expressApollo';
import {
processRequest as processFileUploads,
GraphQLUpload,
} from 'apollo-upload-server';
const gql = String.raw;
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>;
}
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();
}
};
export const registerServer = async ({
app,
server,
path,
cors,
bodyParserConfig,
disableHealthCheck,
onHealthCheck,
uploads,
}: ServerRegistration) => {
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,
);
}
// XXX multiple paths?
server.use({
path,
getHttp: () => createServer(app),
});
app.use(
path,
corsMiddleware(cors),
json(bodyParserConfig),
uploadsMiddleware ? uploadsMiddleware : (req, res, next) => next(),
(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';
if (prefersHTML) {
return gui({
endpoint: path,
subscriptionEndpoint: server.subscriptionsPath,
})(req, res, next);
}
}
return graphqlExpress(server.graphQLServerOptionsForRequest.bind(server))(
req,
res,
next,
);
},
);
};