-
Notifications
You must be signed in to change notification settings - Fork 2k
/
runHttpQuery.ts
462 lines (411 loc) · 14 KB
/
runHttpQuery.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
import { Request, Headers, ValueOrPromise } from 'apollo-server-env';
import {
default as GraphQLOptions,
resolveGraphqlOptions,
} from './graphqlOptions';
import {
ApolloError,
formatApolloErrors,
PersistedQueryNotSupportedError,
PersistedQueryNotFoundError,
hasPersistedQueryError,
} from 'apollo-server-errors';
import {
processGraphQLRequest,
GraphQLRequest,
InvalidGraphQLRequestError,
GraphQLRequestContext,
GraphQLResponse,
} from './requestPipeline';
import { CacheControlExtensionOptions } from 'apollo-cache-control';
import { ApolloServerPlugin } from 'apollo-server-plugin-base';
import { WithRequired, GraphQLExecutionResult } from 'apollo-server-types';
export interface HttpQueryRequest {
method: string;
// query is either the POST body or the GET query string map. In the GET
// case, all values are strings and need to be parsed as JSON; in the POST
// case they should already be parsed. query has keys like 'query' (whose
// value should always be a string), 'variables', 'operationName',
// 'extensions', etc.
query: Record<string, any> | Array<Record<string, any>>;
options:
| GraphQLOptions
| ((...args: Array<any>) => ValueOrPromise<GraphQLOptions>);
request: Pick<Request, 'url' | 'method' | 'headers'>;
}
export interface ApolloServerHttpResponse {
headers?: Record<string, string>;
// ResponseInit contains the follow, which we do not use
// status?: number;
// statusText?: string;
}
export interface HttpQueryResponse {
// FIXME: This isn't actually an individual GraphQL response, but the body
// of the HTTP response, which could contain multiple GraphQL responses
// when using batching.
graphqlResponse: string;
responseInit: ApolloServerHttpResponse;
}
export class HttpQueryError extends Error {
public statusCode: number;
public isGraphQLError: boolean;
public headers?: { [key: string]: string };
constructor(
statusCode: number,
message: string,
isGraphQLError: boolean = false,
headers?: { [key: string]: string },
) {
super(message);
this.name = 'HttpQueryError';
this.statusCode = statusCode;
this.isGraphQLError = isGraphQLError;
this.headers = headers;
}
}
/**
* If options is specified, then the errors array will be formatted
*/
export function throwHttpGraphQLError<E extends Error>(
statusCode: number,
errors: Array<E>,
options?: Pick<GraphQLOptions, 'debug' | 'formatError'>,
extensions?: GraphQLExecutionResult['extensions'],
): never {
const defaultHeaders = { 'Content-Type': 'application/json' };
// force no-cache on PersistedQuery errors
const headers = hasPersistedQueryError(errors)
? {
...defaultHeaders,
'Cache-Control': 'private, no-cache, must-revalidate',
}
: defaultHeaders;
type Result =
& Pick<GraphQLExecutionResult, 'extensions'>
& { errors: E[] | ApolloError[] }
const result: Result = {
errors: options
? formatApolloErrors(errors, {
debug: options.debug,
formatter: options.formatError,
})
: errors,
};
if (extensions) {
result.extensions = extensions;
}
throw new HttpQueryError(
statusCode,
prettyJSONStringify(result),
true,
headers,
);
}
export async function runHttpQuery(
handlerArguments: Array<any>,
request: HttpQueryRequest,
): Promise<HttpQueryResponse> {
let options: GraphQLOptions;
const debugDefault =
process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test';
try {
options = await resolveGraphqlOptions(request.options, ...handlerArguments);
} catch (e) {
// The options can be generated asynchronously, so we don't have access to
// the normal options provided by the user, such as: formatError,
// debug. Therefore, we need to do some unnatural things, such
// as use NODE_ENV to determine the debug settings
e.message = `Invalid options provided to ApolloServer: ${e.message}`;
if (!debugDefault) {
e.warning = `To remove the stacktrace, set the NODE_ENV environment variable to production if the options creation can fail`;
}
return throwHttpGraphQLError(500, [e], { debug: debugDefault });
}
if (options.debug === undefined) {
options.debug = debugDefault;
}
// FIXME: Errors thrown while resolving the context in
// ApolloServer#graphQLServerOptions are currently converted to
// a throwing function, which we invoke here to rethrow an HTTP error.
// When we refactor the integration between ApolloServer, the middleware and
// runHttpQuery, we should pass the original context function through,
// so we can resolve it on every GraphQL request (as opposed to once per HTTP
// request, which could be a batch).
if (typeof options.context === 'function') {
try {
(options.context as () => never)();
} catch (e) {
e.message = `Context creation failed: ${e.message}`;
// For errors that are not internal, such as authentication, we
// should provide a 400 response
if (
e.extensions &&
e.extensions.code &&
e.extensions.code !== 'INTERNAL_SERVER_ERROR'
) {
return throwHttpGraphQLError(400, [e], options);
} else {
return throwHttpGraphQLError(500, [e], options);
}
}
}
const config = {
schema: options.schema,
rootValue: options.rootValue,
context: options.context || {},
validationRules: options.validationRules,
executor: options.executor,
fieldResolver: options.fieldResolver,
// FIXME: Use proper option types to ensure this
// The cache is guaranteed to be initialized in ApolloServer, and
// cacheControl defaults will also have been set if a boolean argument is
// passed in.
cache: options.cache!,
cacheControl: options.cacheControl as
| CacheControlExtensionOptions
| undefined,
dataSources: options.dataSources,
documentStore: options.documentStore,
extensions: options.extensions,
persistedQueries: options.persistedQueries,
tracing: options.tracing,
formatError: options.formatError,
formatResponse: options.formatResponse,
debug: options.debug,
plugins: options.plugins || [],
reporting: options.reporting,
};
return processHTTPRequest(config, request);
}
export async function processHTTPRequest<TContext>(
options: WithRequired<GraphQLOptions<TContext>, 'cache' | 'plugins'> & {
context: TContext;
},
httpRequest: HttpQueryRequest,
): Promise<HttpQueryResponse> {
let requestPayload;
switch (httpRequest.method) {
case 'POST':
if (!httpRequest.query || Object.keys(httpRequest.query).length === 0) {
throw new HttpQueryError(
500,
'POST body missing. Did you forget use body-parser middleware?',
);
}
requestPayload = httpRequest.query;
break;
case 'GET':
if (!httpRequest.query || Object.keys(httpRequest.query).length === 0) {
throw new HttpQueryError(400, 'GET query missing.');
}
requestPayload = httpRequest.query;
break;
default:
throw new HttpQueryError(
405,
'Apollo Server supports only GET/POST requests.',
false,
{
Allow: 'GET, POST',
},
);
}
// Create a local copy of `options`, based on global options, but maintaining
// that appropriate plugins are in place.
options = {
...options,
plugins: [checkOperationPlugin, ...options.plugins],
};
function buildRequestContext(
request: GraphQLRequest,
): GraphQLRequestContext<TContext> {
// FIXME: We currently shallow clone the context for every request,
// but that's unlikely to be what people want.
// We allow passing in a function for `context` to ApolloServer,
// but this only runs once for a batched request (because this is resolved
// in ApolloServer#graphQLServerOptions, before runHttpQuery is invoked).
const context = cloneObject(options.context);
return {
request,
response: {
http: {
headers: new Headers(),
},
},
context,
cache: options.cache,
debug: options.debug,
metrics: {
captureTraces: !!options.reporting,
},
};
}
const responseInit: ApolloServerHttpResponse = {
headers: {
'Content-Type': 'application/json',
},
};
let body: string;
try {
if (Array.isArray(requestPayload)) {
// We're processing a batch request
const requests = requestPayload.map(requestParams =>
parseGraphQLRequest(httpRequest.request, requestParams),
);
const responses = await Promise.all(
requests.map(async request => {
try {
const requestContext = buildRequestContext(request);
return await processGraphQLRequest(options, requestContext);
} catch (error) {
// A batch can contain another query that returns data,
// so we don't error out the entire request with an HttpError
return {
errors: formatApolloErrors([error], options),
};
}
}),
);
body = prettyJSONStringify(responses.map(serializeGraphQLResponse));
} else {
// We're processing a normal request
const request = parseGraphQLRequest(httpRequest.request, requestPayload);
try {
const requestContext = buildRequestContext(request);
const response = await processGraphQLRequest(options, requestContext);
// This code is run on parse/validation errors and any other error that
// doesn't reach GraphQL execution
if (response.errors && typeof response.data === 'undefined') {
// don't include options, since the errors have already been formatted
return throwHttpGraphQLError(
(response.http && response.http.status) || 400,
response.errors as any,
undefined,
response.extensions,
);
}
if (response.http) {
for (const [name, value] of response.http.headers) {
responseInit.headers![name] = value;
}
}
body = prettyJSONStringify(serializeGraphQLResponse(response));
} catch (error) {
if (error instanceof InvalidGraphQLRequestError) {
throw new HttpQueryError(400, error.message);
} else if (
error instanceof PersistedQueryNotSupportedError ||
error instanceof PersistedQueryNotFoundError
) {
return throwHttpGraphQLError(200, [error], options);
} else {
throw error;
}
}
}
} catch (error) {
if (error instanceof HttpQueryError) {
throw error;
}
return throwHttpGraphQLError(500, [error], options);
}
responseInit.headers!['Content-Length'] = Buffer.byteLength(
body,
'utf8',
).toString();
return {
graphqlResponse: body,
responseInit,
};
}
function parseGraphQLRequest(
httpRequest: Pick<Request, 'url' | 'method' | 'headers'>,
requestParams: Record<string, any>,
): GraphQLRequest {
let queryString: string | undefined = requestParams.query;
let extensions = requestParams.extensions;
if (typeof extensions === 'string' && extensions !== '') {
// For GET requests, we have to JSON-parse extensions. (For POST
// requests they get parsed as part of parsing the larger body they're
// inside.)
try {
extensions = JSON.parse(extensions);
} catch (error) {
throw new HttpQueryError(400, 'Extensions are invalid JSON.');
}
}
if (queryString && typeof queryString !== 'string') {
// Check for a common error first.
if ((queryString as any).kind === 'Document') {
throw new HttpQueryError(
400,
"GraphQL queries must be strings. It looks like you're sending the " +
'internal graphql-js representation of a parsed query in your ' +
'request instead of a request in the GraphQL query language. You ' +
'can convert an AST to a string using the `print` function from ' +
'`graphql`, or use a client like `apollo-client` which converts ' +
'the internal representation to a string for you.',
);
} else {
throw new HttpQueryError(400, 'GraphQL queries must be strings.');
}
}
const operationName = requestParams.operationName;
let variables = requestParams.variables;
if (typeof variables === 'string' && variables !== '') {
try {
// XXX Really we should only do this for GET requests, but for
// compatibility reasons we'll keep doing this at least for now for
// broken clients that ship variables in a string for no good reason.
variables = JSON.parse(variables);
} catch (error) {
throw new HttpQueryError(400, 'Variables are invalid JSON.');
}
}
return {
query: queryString,
operationName,
variables,
extensions,
http: httpRequest,
};
}
// GET operations should only be queries (not mutations). We want to throw
// a particular HTTP error in that case.
const checkOperationPlugin: ApolloServerPlugin = {
requestDidStart() {
return {
didResolveOperation({ request, operation }) {
if (!request.http) return;
if (request.http.method === 'GET' && operation.operation !== 'query') {
throw new HttpQueryError(
405,
`GET supports only query operation`,
false,
{
Allow: 'POST',
},
);
}
},
};
},
};
function serializeGraphQLResponse(
response: GraphQLResponse,
): Pick<GraphQLResponse, 'errors' | 'data' | 'extensions'> {
// See https://github.com/facebook/graphql/pull/384 for why
// errors comes first.
return {
errors: response.errors,
data: response.data,
extensions: response.extensions,
};
}
// The result of a curl does not appear well in the terminal, so we add an extra new line
function prettyJSONStringify(value: any) {
return JSON.stringify(value) + '\n';
}
function cloneObject<T extends Object>(object: T): T {
return Object.assign(Object.create(Object.getPrototypeOf(object)), object);
}