-
Notifications
You must be signed in to change notification settings - Fork 2k
/
ApolloServer.ts
212 lines (191 loc) · 7.29 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
210
211
212
import {
APIGatewayProxyCallback,
APIGatewayProxyEvent,
Context as LambdaContext,
} from 'aws-lambda';
import { ApolloServerBase, GraphQLOptions, Config } from 'apollo-server-core';
import {
renderPlaygroundPage,
RenderPageOptions as PlaygroundRenderPageOptions,
} from '@apollographql/graphql-playground-html';
import { graphqlLambda } from './lambdaApollo';
import { Headers } from 'apollo-server-env';
export interface CreateHandlerOptions {
cors?: {
origin?: boolean | string | string[];
methods?: string | string[];
allowedHeaders?: string | string[];
exposedHeaders?: string | string[];
credentials?: boolean;
maxAge?: number;
};
}
export class ApolloServer extends ApolloServerBase {
// If you feel tempted to add an option to this constructor. Please consider
// another place, since the documentation becomes much more complicated when
// the constructor is not longer shared between all integration
constructor(options: Config) {
if (process.env.ENGINE_API_KEY || options.engine) {
options.engine = {
sendReportsImmediately: true,
...(typeof options.engine !== 'boolean' ? options.engine : {}),
};
}
super(options);
}
// 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
createGraphQLServerOptions(
event: APIGatewayProxyEvent,
context: LambdaContext,
): Promise<GraphQLOptions> {
return super.graphQLServerOptions({ event, context });
}
public createHandler({ cors }: CreateHandlerOptions = { cors: undefined }) {
// We will kick off the `willStart` event once for the server, and then
// await it before processing any requests by incorporating its `await` into
// the GraphQLServerOptions function which is called before each request.
const promiseWillStart = this.willStart();
const corsHeaders = new Headers();
if (cors) {
if (cors.methods) {
if (typeof cors.methods === 'string') {
corsHeaders.set('access-control-allow-methods', cors.methods);
} else if (Array.isArray(cors.methods)) {
corsHeaders.set(
'access-control-allow-methods',
cors.methods.join(','),
);
}
}
if (cors.allowedHeaders) {
if (typeof cors.allowedHeaders === 'string') {
corsHeaders.set('access-control-allow-headers', cors.allowedHeaders);
} else if (Array.isArray(cors.allowedHeaders)) {
corsHeaders.set(
'access-control-allow-headers',
cors.allowedHeaders.join(','),
);
}
}
if (cors.exposedHeaders) {
if (typeof cors.exposedHeaders === 'string') {
corsHeaders.set('access-control-expose-headers', cors.exposedHeaders);
} else if (Array.isArray(cors.exposedHeaders)) {
corsHeaders.set(
'access-control-expose-headers',
cors.exposedHeaders.join(','),
);
}
}
if (cors.credentials) {
corsHeaders.set('access-control-allow-credentials', 'true');
}
if (typeof cors.maxAge === 'number') {
corsHeaders.set('access-control-max-age', cors.maxAge.toString());
}
}
return (
event: APIGatewayProxyEvent,
context: LambdaContext,
callback: APIGatewayProxyCallback,
) => {
// We re-load the headers into a Fetch API-compatible `Headers`
// interface within `graphqlLambda`, but we still need to respect the
// case-insensitivity within this logic here, so we'll need to do it
// twice since it's not accessible to us otherwise, right now.
const eventHeaders = new Headers(event.headers);
// Make a request-specific copy of the CORS headers, based on the server
// global CORS headers we've set above.
const requestCorsHeaders = new Headers(corsHeaders);
if (cors && cors.origin) {
const requestOrigin = eventHeaders.get('origin');
if (typeof cors.origin === 'string') {
requestCorsHeaders.set('access-control-allow-origin', cors.origin);
} else if (
requestOrigin &&
(typeof cors.origin === 'boolean' ||
(Array.isArray(cors.origin) &&
requestOrigin &&
cors.origin.includes(requestOrigin)))
) {
requestCorsHeaders.set('access-control-allow-origin', requestOrigin);
}
const requestAccessControlRequestHeaders = eventHeaders.get(
'access-control-request-headers',
);
if (!cors.allowedHeaders && requestAccessControlRequestHeaders) {
requestCorsHeaders.set(
'access-control-allow-headers',
requestAccessControlRequestHeaders,
);
}
}
// Convert the `Headers` into an object which can be spread into the
// various headers objects below.
// Note: while Object.fromEntries simplifies this code, it's only currently
// supported in Node 12 (we support >=6)
const requestCorsHeadersObject = Array.from(requestCorsHeaders).reduce<
Record<string, string>
>((headersObject, [key, value]) => {
headersObject[key] = value;
return headersObject;
}, {});
if (event.httpMethod === 'OPTIONS') {
context.callbackWaitsForEmptyEventLoop = false;
return callback(null, {
body: '',
statusCode: 204,
headers: {
...requestCorsHeadersObject,
},
});
}
if (this.playgroundOptions && event.httpMethod === 'GET') {
const acceptHeader = event.headers['Accept'] || event.headers['accept'];
if (acceptHeader && acceptHeader.includes('text/html')) {
const path =
event.path ||
(event.requestContext && event.requestContext.path) ||
'/';
const playgroundRenderPageOptions: PlaygroundRenderPageOptions = {
endpoint: path,
...this.playgroundOptions,
};
return callback(null, {
body: renderPlaygroundPage(playgroundRenderPageOptions),
statusCode: 200,
headers: {
'Content-Type': 'text/html',
...requestCorsHeadersObject,
},
});
}
}
const callbackFilter: APIGatewayProxyCallback = (error, result) => {
callback(
error,
result && {
...result,
headers: {
...result.headers,
...requestCorsHeadersObject,
},
},
);
};
graphqlLambda(async () => {
// In a world where this `createHandler` was async, we might avoid this
// but since we don't want to introduce a breaking change to this API
// (by switching it to `async`), we'll leverage the
// `GraphQLServerOptions`, which are dynamically built on each request,
// to `await` the `promiseWillStart` which we kicked off at the top of
// this method to ensure that it runs to completion (which is part of
// its contract) prior to processing the request.
await promiseWillStart;
return this.createGraphQLServerOptions(event, context);
})(event, context, callbackFilter);
};
}
}