-
Notifications
You must be signed in to change notification settings - Fork 2k
/
ApolloServer.ts
209 lines (186 loc) · 6.5 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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import Koa from 'koa';
import corsMiddleware from '@koa/cors';
import bodyParser from 'koa-bodyparser';
import compose from 'koa-compose';
import {
renderPlaygroundPage,
RenderPageOptions as PlaygroundRenderPageOptions,
} from '@apollographql/graphql-playground-html';
import {
ApolloServerBase,
formatApolloErrors,
processFileUploads,
} from 'apollo-server-core';
import accepts from 'accepts';
import typeis from 'type-is';
import { graphqlKoa } from './koaApollo';
export { GraphQLOptions, GraphQLExtension } from 'apollo-server-core';
import { GraphQLOptions, FileUploadOptions } from 'apollo-server-core';
export interface ServerRegistration {
app: Koa;
path?: string;
cors?: corsMiddleware.Options | boolean;
bodyParserConfig?: bodyParser.Options | boolean;
onHealthCheck?: (ctx: Koa.Context) => Promise<any>;
disableHealthCheck?: boolean;
}
const fileUploadMiddleware = (
uploadsConfig: FileUploadOptions,
server: ApolloServerBase,
) => async (ctx: Koa.Context, next: Function) => {
if (typeis(ctx.req, ['multipart/form-data'])) {
try {
ctx.request.body = await processFileUploads(
ctx.req,
ctx.res,
uploadsConfig,
);
return next();
} catch (error) {
if (error.status && error.expose) ctx.status = error.status;
throw formatApolloErrors([error], {
formatter: server.requestOptions.formatError,
debug: server.requestOptions.debug,
});
}
} else {
return next();
}
};
const middlewareFromPath = (
path: string,
middleware: compose.Middleware<Koa.Context>,
) => (ctx: Koa.Context, next: () => Promise<any>) => {
if (ctx.path === path) {
return middleware(ctx, next);
} else {
return next();
}
};
export class ApolloServer extends ApolloServerBase {
// This translates the arguments from the middleware into graphQL options It
// provides typings for the integration specific behavior, ideally this would
// be propagated with a generic to the super class
async createGraphQLServerOptions(ctx: Koa.Context): Promise<GraphQLOptions> {
return super.graphQLServerOptions({ ctx });
}
protected supportsSubscriptions(): boolean {
return true;
}
protected supportsUploads(): boolean {
return true;
}
// TODO: While Koa is Promise-aware, this API hasn't been historically, even
// though other integration's (e.g. Hapi) implementations of this method
// are `async`. Therefore, this should become `async` in a major release in
// order to align the API with other integrations.
public applyMiddleware({
app,
path,
cors,
bodyParserConfig,
disableHealthCheck,
onHealthCheck,
}: ServerRegistration) {
if (!path) path = '/graphql';
// Despite the fact that this `applyMiddleware` function is `async` in
// other integrations (e.g. Hapi), currently it is not for Koa (@here).
// That should change in a future version, but that would be a breaking
// change right now (see comment above this method's declaration above).
//
// That said, we do need to await the `willStart` lifecycle event which
// can perform work prior to serving a request. While we could do this
// via awaiting in a Koa middleware, well kick off `willStart` right away,
// so hopefully it'll finish before the first request comes in. We won't
// call `next` until it's ready, which will effectively yield until that
// work has finished. Any errors will be surfaced to Koa through its own
// native Promise-catching facilities.
const promiseWillStart = this.willStart();
app.use(
middlewareFromPath(path, async (_ctx: Koa.Context, next: Function) => {
await promiseWillStart;
return next();
}),
);
if (!disableHealthCheck) {
app.use(
middlewareFromPath(
'/.well-known/apollo/server-health',
(ctx: Koa.Context) => {
// Response follows https://tools.ietf.org/html/draft-inadarei-api-health-check-01
ctx.set('Content-Type', 'application/health+json');
if (onHealthCheck) {
return onHealthCheck(ctx)
.then(() => {
ctx.body = { status: 'pass' };
})
.catch(() => {
ctx.status = 503;
ctx.body = { status: 'fail' };
});
} else {
ctx.body = { status: 'pass' };
}
},
),
);
}
let uploadsMiddleware;
if (this.uploadsConfig && typeof processFileUploads === 'function') {
uploadsMiddleware = fileUploadMiddleware(this.uploadsConfig, this);
}
this.graphqlPath = path;
if (cors === true) {
app.use(middlewareFromPath(path, corsMiddleware()));
} else if (cors !== false) {
app.use(middlewareFromPath(path, corsMiddleware(cors)));
}
if (bodyParserConfig === true) {
app.use(middlewareFromPath(path, bodyParser()));
} else if (bodyParserConfig !== false) {
app.use(middlewareFromPath(path, bodyParser(bodyParserConfig)));
}
if (uploadsMiddleware) {
app.use(middlewareFromPath(path, uploadsMiddleware));
}
app.use(
middlewareFromPath(path, (ctx: Koa.Context, next: Function) => {
if (ctx.request.method === 'OPTIONS') {
ctx.status = 204;
ctx.body = '';
return;
}
if (this.playgroundOptions && ctx.request.method === 'GET') {
// perform more expensive content-type check only if necessary
const accept = accepts(ctx.req);
const types = accept.types() as string[];
const prefersHTML =
types.find(
(x: string) => x === 'text/html' || x === 'application/json',
) === 'text/html';
if (prefersHTML) {
const playgroundRenderPageOptions: PlaygroundRenderPageOptions = {
endpoint: path,
subscriptionEndpoint: this.subscriptionsPath,
...this.playgroundOptions,
};
ctx.set('Content-Type', 'text/html');
const playground = renderPlaygroundPage(
playgroundRenderPageOptions,
);
ctx.body = playground;
return;
}
}
return graphqlKoa(() => {
return this.createGraphQLServerOptions(ctx);
})(ctx, next);
}),
);
}
}
export const registerServer = () => {
throw new Error(
'Please use server.applyMiddleware instead of registerServer. This warning will be removed in the next release',
);
};