This repository was archived by the owner on Mar 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 535
/
Copy pathindex.js
602 lines (524 loc) · 19.1 KB
/
index.js
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
// @flow strict
import { type IncomingMessage, type ServerResponse } from 'http';
import url from 'url';
import accepts from 'accepts';
import httpError from 'http-errors';
import {
Source,
parse,
validate,
execute,
formatError,
validateSchema,
getOperationAST,
specifiedRules,
type ASTVisitor,
type DocumentNode,
type ValidationRule,
type ValidationContext,
type ExecutionArgs,
type ExecutionResult,
type GraphQLError,
type GraphQLSchema,
type GraphQLFieldResolver,
type GraphQLTypeResolver,
} from 'graphql';
import { parseBody } from './parseBody';
import { renderGraphiQL, type GraphiQLOptions } from './renderGraphiQL';
type $Request = IncomingMessage;
type $Response = ServerResponse & {| json?: ?(data: mixed) => void |};
/**
* Used to configure the graphqlHTTP middleware by providing a schema
* and other configuration options.
*
* Options can be provided as an Object, a Promise for an Object, or a Function
* that returns an Object or a Promise for an Object.
*/
export type Options =
| ((
request: $Request,
response: $Response,
params?: GraphQLParams,
) => OptionsResult)
| OptionsResult;
export type OptionsResult = OptionsData | Promise<OptionsData>;
export type OptionsData = {|
/**
* A GraphQL schema from graphql-js.
*/
schema: GraphQLSchema,
/**
* A value to pass as the context to this middleware.
*/
context?: ?mixed,
/**
* An object to pass as the rootValue to the graphql() function.
*/
rootValue?: ?mixed,
/**
* A boolean to configure whether the output should be pretty-printed.
*/
pretty?: ?boolean,
/**
* An optional array of validation rules that will be applied on the document
* in additional to those defined by the GraphQL spec.
*/
validationRules?: ?$ReadOnlyArray<(ValidationContext) => ASTVisitor>,
/**
* An optional function which will be used to validate instead of default `validate`
* from `graphql-js`.
*/
customValidateFn?: ?(
schema: GraphQLSchema,
documentAST: DocumentNode,
rules: $ReadOnlyArray<ValidationRule>,
) => $ReadOnlyArray<GraphQLError>,
/**
* An optional function which will be used to execute instead of default `execute`
* from `graphql-js`.
*/
customExecuteFn?: ?(args: ExecutionArgs) => Promise<ExecutionResult>,
/**
* An optional function which will be used to format any errors produced by
* fulfilling a GraphQL operation. If no function is provided, GraphQL's
* default spec-compliant `formatError` function will be used.
*/
customFormatErrorFn?: ?(error: GraphQLError) => mixed,
/**
* An optional function which will be used to create a document instead of
* the default `parse` from `graphql-js`.
*/
customParseFn?: ?(source: Source) => DocumentNode,
/**
* `formatError` is deprecated and replaced by `customFormatErrorFn`. It will
* be removed in version 1.0.0.
*/
formatError?: ?(error: GraphQLError) => mixed,
/**
* An optional function for adding additional metadata to the GraphQL response
* as a key-value object. The result will be added to "extensions" field in
* the resulting JSON. This is often a useful place to add development time
* info such as the runtime of a query or the amount of resources consumed.
*
* Information about the request is provided to be used.
*
* This function may be async.
*/
extensions?: ?(info: RequestInfo) => { [key: string]: mixed, ... },
/**
* A boolean to optionally enable GraphiQL mode.
* Alternatively, instead of `true` you can pass in an options object.
*/
graphiql?: ?boolean | ?GraphiQLOptions,
/**
* A resolver function to use when one is not provided by the schema.
* If not provided, the default field resolver is used (which looks for a
* value or method on the source value with the field's name).
*/
fieldResolver?: ?GraphQLFieldResolver<mixed, mixed>,
/**
* A type resolver function to use when none is provided by the schema.
* If not provided, the default type resolver is used (which looks for a
* `__typename` field or alternatively calls the `isTypeOf` method).
*/
typeResolver?: ?GraphQLTypeResolver<mixed, mixed>,
/**
* A optional string which will used to predefined fragments
*/
serverFragments?: ?string,
|};
/**
* All information about a GraphQL request.
*/
export type RequestInfo = {|
/**
* The parsed GraphQL document.
*/
document: ?DocumentNode,
/**
* The variable values used at runtime.
*/
variables: ?{ +[name: string]: mixed, ... },
/**
* The (optional) operation name requested.
*/
operationName: ?string,
/**
* The result of executing the operation.
*/
result: ?ExecutionResult,
/**
* A value to pass as the context to the graphql() function.
*/
context?: ?mixed,
|};
type Middleware = (request: $Request, response: $Response) => Promise<void>;
/**
* Middleware for express; takes an options object or function as input to
* configure behavior, and returns an express middleware.
*/
module.exports = graphqlHTTP;
function graphqlHTTP(options: Options): Middleware {
if (!options) {
throw new Error('GraphQL middleware requires options.');
}
return function graphqlMiddleware(request: $Request, response: $Response) {
// Higher scoped variables are referred to at various stages in the
// asynchronous state machine below.
let context;
let params;
let pretty;
let formatErrorFn = formatError;
let validateFn = validate;
let executeFn = execute;
let parseFn = parse;
let extensionsFn;
let showGraphiQL = false;
let query;
let documentAST;
let variables;
let operationName;
// Promises are used as a mechanism for capturing any thrown errors during
// the asynchronous process below.
// Parse the Request to get GraphQL request parameters.
return getGraphQLParams(request)
.then(
graphQLParams => {
params = graphQLParams;
// Then, resolve the Options to get OptionsData.
return resolveOptions(params);
},
error => {
// When we failed to parse the GraphQL parameters, we still need to get
// the options object, so make an options call to resolve just that.
const dummyParams = {
query: null,
variables: null,
operationName: null,
raw: null,
};
return resolveOptions(dummyParams).then(() => Promise.reject(error));
},
)
.then(optionsData => {
// Assert that schema is required.
if (!optionsData.schema) {
throw new Error('GraphQL middleware options must contain a schema.');
}
// Collect information from the options data object.
const schema = optionsData.schema;
const rootValue = optionsData.rootValue;
const fieldResolver = optionsData.fieldResolver;
const typeResolver = optionsData.typeResolver;
const validationRules = optionsData.validationRules || [];
const graphiql = optionsData.graphiql;
const serverFragments = optionsData.serverFragments;
context = optionsData.context || request;
// GraphQL HTTP only supports GET and POST methods.
if (request.method !== 'GET' && request.method !== 'POST') {
response.setHeader('Allow', 'GET, POST');
throw httpError(405, 'GraphQL only supports GET and POST requests.');
}
// Get GraphQL params from the request and POST body data.
query = serverFragments ? addServerFragments(serverFragments, params.query) : params.query;
variables = params.variables;
operationName = params.operationName;
showGraphiQL = canDisplayGraphiQL(request, params) && graphiql;
// If there is no query, but GraphiQL will be displayed, do not produce
// a result, otherwise return a 400: Bad Request.
if (query == null) {
if (showGraphiQL) {
return null;
}
throw httpError(400, 'Must provide query string.');
}
// Validate Schema
const schemaValidationErrors = validateSchema(schema);
if (schemaValidationErrors.length > 0) {
// Return 500: Internal Server Error if invalid schema.
response.statusCode = 500;
return { errors: schemaValidationErrors };
}
// GraphQL source.
const source = new Source(query, 'GraphQL request');
// Parse source to AST, reporting any syntax error.
try {
documentAST = parseFn(source);
} catch (syntaxError) {
// Return 400: Bad Request if any syntax errors errors exist.
response.statusCode = 400;
return { errors: [syntaxError] };
}
// Validate AST, reporting any errors.
const validationErrors = validateFn(schema, documentAST, [
...specifiedRules,
...validationRules,
]);
if (validationErrors.length > 0) {
// Return 400: Bad Request if any validation errors exist.
response.statusCode = 400;
return { errors: validationErrors };
}
// Only query operations are allowed on GET requests.
if (request.method === 'GET') {
// Determine if this GET request will perform a non-query.
const operationAST = getOperationAST(documentAST, operationName);
if (operationAST && operationAST.operation !== 'query') {
// If GraphiQL can be shown, do not perform this query, but
// provide it to GraphiQL so that the requester may perform it
// themselves if desired.
if (showGraphiQL) {
return null;
}
// Otherwise, report a 405: Method Not Allowed error.
response.setHeader('Allow', 'POST');
throw httpError(
405,
`Can only perform a ${operationAST.operation} operation from a POST request.`,
);
}
}
// Perform the execution, reporting any errors creating the context.
try {
return executeFn({
schema,
document: documentAST,
rootValue,
contextValue: context,
variableValues: variables,
operationName,
fieldResolver,
typeResolver,
});
} catch (contextError) {
// Return 400: Bad Request if any execution context errors exist.
response.statusCode = 400;
return { errors: [contextError] };
}
})
.then(result => {
// Collect and apply any metadata extensions if a function was provided.
// https://graphql.github.io/graphql-spec/#sec-Response-Format
if (result && extensionsFn) {
return Promise.resolve(
extensionsFn({
document: documentAST,
variables,
operationName,
result,
context,
}),
).then(extensions => {
if (extensions && typeof extensions === 'object') {
(result: any).extensions = extensions;
}
return result;
});
}
return result;
})
.catch(error => {
// If an error was caught, report the httpError status, or 500.
response.statusCode = error.status || 500;
return { errors: [error] };
})
.then(result => {
// If no data was included in the result, that indicates a runtime query
// error, indicate as such with a generic status code.
// Note: Information about the error itself will still be contained in
// the resulting JSON payload.
// https://graphql.github.io/graphql-spec/#sec-Data
if (response.statusCode === 200 && result && !result.data) {
response.statusCode = 500;
}
// Format any encountered errors.
if (result && result.errors) {
(result: any).errors = result.errors.map(formatErrorFn);
}
// If allowed to show GraphiQL, present it instead of JSON.
if (showGraphiQL) {
const payload = renderGraphiQL({
query,
variables,
operationName,
result,
options: typeof showGraphiQL !== 'boolean' ? showGraphiQL : {},
});
return sendResponse(response, 'text/html', payload);
}
// At this point, result is guaranteed to exist, as the only scenario
// where it will not is when showGraphiQL is true.
if (!result) {
throw httpError(500, 'Internal Error');
}
// If "pretty" JSON isn't requested, and the server provides a
// response.json method (express), use that directly.
// Otherwise use the simplified sendResponse method.
if (!pretty && typeof response.json === 'function') {
response.json(result);
} else {
const payload = JSON.stringify(result, null, pretty ? 2 : 0);
sendResponse(response, 'application/json', payload);
}
});
async function resolveOptions(requestParams) {
const optionsResult =
typeof options === 'function'
? options(request, response, requestParams)
: options;
const optionsData = await optionsResult;
// Assert that optionsData is in fact an Object.
if (!optionsData || typeof optionsData !== 'object') {
throw new Error(
'GraphQL middleware option function must return an options object or a promise which will be resolved to an options object.',
);
}
if (optionsData.formatError) {
// eslint-disable-next-line no-console
console.warn(
'`formatError` is deprecated and replaced by `customFormatErrorFn`. It will be removed in version 1.0.0.',
);
}
validateFn = optionsData.customValidateFn || validateFn;
executeFn = optionsData.customExecuteFn || executeFn;
parseFn = optionsData.customParseFn || parseFn;
formatErrorFn =
optionsData.customFormatErrorFn ||
optionsData.formatError ||
formatErrorFn;
extensionsFn = optionsData.extensions;
pretty = optionsData.pretty;
return optionsData;
}
};
}
export type GraphQLParams = {|
query: ?string,
variables: ?{ +[name: string]: mixed, ... },
operationName: ?string,
raw: ?boolean,
|};
/**
* Provided a "Request" provided by express or connect (typically a node style
* HTTPClientRequest), Promise the GraphQL request parameters.
*/
module.exports.getGraphQLParams = getGraphQLParams;
async function getGraphQLParams(request: $Request): Promise<GraphQLParams> {
const bodyData = await parseBody(request);
const urlData = (request.url && url.parse(request.url, true).query) || {};
return parseGraphQLParams(urlData, bodyData);
}
/**
* Helper function to get the GraphQL params from the request.
*/
function parseGraphQLParams(
urlData: { [param: string]: mixed, ... },
bodyData: { [param: string]: mixed, ... },
): GraphQLParams {
// GraphQL Query string.
let query = urlData.query || bodyData.query;
if (typeof query !== 'string') {
query = null;
}
// Parse the variables if needed.
let variables = urlData.variables || bodyData.variables;
if (typeof variables === 'string') {
try {
variables = JSON.parse(variables);
} catch (error) {
throw httpError(400, 'Variables are invalid JSON.');
}
} else if (typeof variables !== 'object') {
variables = null;
}
// Name of GraphQL operation to execute.
let operationName = urlData.operationName || bodyData.operationName;
if (typeof operationName !== 'string') {
operationName = null;
}
const raw = urlData.raw !== undefined || bodyData.raw !== undefined;
return { query, variables, operationName, raw };
}
/**
* Helper function to determine if GraphiQL can be displayed.
*/
function canDisplayGraphiQL(request: $Request, params: GraphQLParams): boolean {
// If `raw` exists, GraphiQL mode is not enabled.
// Allowed to show GraphiQL if not requested as raw and this request
// prefers HTML over JSON.
return !params.raw && accepts(request).types(['json', 'html']) === 'html';
}
/**
* Helper function for sending a response using only the core Node server APIs.
*/
function sendResponse(response: $Response, type: string, data: string): void {
const chunk = Buffer.from(data, 'utf8');
response.setHeader('Content-Type', type + '; charset=utf-8');
response.setHeader('Content-Length', String(chunk.length));
response.end(chunk);
}
/**
* Helper function to get the first word from string.
*
* @param { string } text - The full string.
*
* @returns { string } - First word.
*/
function sliceFirstWord(text: string): string {
let slicedText = text;
const firstSpaceIndex = slicedText.indexOf(' ');
if(firstSpaceIndex !== -1) {
slicedText = slicedText.slice(0, firstSpaceIndex);
}
const firstEndRowIndex = slicedText.indexOf('\n');
if(firstEndRowIndex !== -1) {
slicedText = slicedText.slice(0, firstEndRowIndex);
}
return slicedText;
}
/**
* Helper recursive function that finds all the fragments from the server that are used in the current request.
*
* @param { string } serverFragments - Fragments from the server.
* @param { string } query - Query from the request.
* @param { Set<string> } fragmentsInUsed - Set of relevant fragments.
*
* @returns { Set<string> } - relevant fragments for current request.
*/
function findFragments(serverFragments: string, query: string, fragmentsInUsed: Set<string>): Set<string> {
// Fragment declaration starts with 'fragment' key word
// Slice to remove text before the first fragment declaration
let fragmentDeclarationFields = serverFragments.split('fragment ').slice(1);
// Fragment variable starts with spread - '...'
// Slice to remove text before the first fragment variable
let fragmentVariableFields = query.split('...').slice(1);
fragmentVariableFields.forEach(fragmentVariable => {
const currFragmentVariableKeyName = sliceFirstWord(fragmentVariable);
for (let index = 0; index < fragmentDeclarationFields.length; index++) {
const currFragmentDeclaration = fragmentDeclarationFields[index];
const currFragmentDeclarationKeyName = sliceFirstWord(currFragmentDeclaration);
if(currFragmentDeclarationKeyName === currFragmentVariableKeyName) {
fragmentsInUsed.add(currFragmentDeclaration);
// Find fragments in the matching fragments
fragmentsInUsed = findFragments(serverFragments, currFragmentDeclaration, fragmentsInUsed)
break;
}
}
})
return fragmentsInUsed;
}
/**
* Add to query the relevant server fragments
*
* @param {*} serverFragments - Fragments from the server.
* @param {*} query - Query from the request.
*
* @returns - Concat relevant fragments to request query
*/
function addServerFragments(serverFragments: string, query: string): string {
let fragmentsInUsed = '';
[...(findFragments(serverFragments, query, new Set()))].forEach(fullFragment => {
fragmentsInUsed += `fragment ${fullFragment} `;
})
return `${fragmentsInUsed}\n${query}`;
}