-
Notifications
You must be signed in to change notification settings - Fork 2k
/
validate.js
731 lines (654 loc) · 20.7 KB
/
validate.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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
*/
import {
isObjectType,
isInterfaceType,
isUnionType,
isEnumType,
isInputObjectType,
isNonNullType,
isNamedType,
isInputType,
isOutputType,
} from './definition';
import type {
GraphQLObjectType,
GraphQLInterfaceType,
GraphQLUnionType,
GraphQLEnumType,
GraphQLInputObjectType,
} from './definition';
import { isDirective } from './directives';
import type { GraphQLDirective } from './directives';
import { isIntrospectionType } from './introspection';
import { isSchema } from './schema';
import type { GraphQLSchema } from './schema';
import find from '../jsutils/find';
import invariant from '../jsutils/invariant';
import objectValues from '../jsutils/objectValues';
import { GraphQLError } from '../error/GraphQLError';
import type {
ASTNode,
FieldDefinitionNode,
EnumValueDefinitionNode,
InputValueDefinitionNode,
NamedTypeNode,
TypeNode,
} from '../language/ast';
import { isValidNameError } from '../utilities/assertValidName';
import { isEqualType, isTypeSubTypeOf } from '../utilities/typeComparators';
/**
* Implements the "Type Validation" sub-sections of the specification's
* "Type System" section.
*
* Validation runs synchronously, returning an array of encountered errors, or
* an empty array if no errors were encountered and the Schema is valid.
*/
export function validateSchema(
schema: GraphQLSchema,
): $ReadOnlyArray<GraphQLError> {
// First check to ensure the provided value is in fact a GraphQLSchema.
invariant(
isSchema(schema),
`Expected ${String(schema)} to be a GraphQL schema.`,
);
// If this Schema has already been validated, return the previous results.
if (schema.__validationErrors) {
return schema.__validationErrors;
}
// Validate the schema, producing a list of errors.
const context = new SchemaValidationContext(schema);
validateRootTypes(context);
validateDirectives(context);
validateTypes(context);
// Persist the results of validation before returning to ensure validation
// does not run multiple times for this schema.
const errors = context.getErrors();
schema.__validationErrors = errors;
return errors;
}
/**
* Utility function which asserts a schema is valid by throwing an error if
* it is invalid.
*/
export function assertValidSchema(schema: GraphQLSchema): void {
const errors = validateSchema(schema);
if (errors.length !== 0) {
throw new Error(errors.map(error => error.message).join('\n\n'));
}
}
class SchemaValidationContext {
+_errors: Array<GraphQLError>;
+schema: GraphQLSchema;
constructor(schema) {
this._errors = [];
this.schema = schema;
}
reportError(
message: string,
nodes?: $ReadOnlyArray<?ASTNode> | ?ASTNode,
): void {
const _nodes = (Array.isArray(nodes) ? nodes : [nodes]).filter(Boolean);
this.addError(new GraphQLError(message, _nodes));
}
addError(error: GraphQLError): void {
this._errors.push(error);
}
getErrors(): $ReadOnlyArray<GraphQLError> {
return this._errors;
}
}
function validateRootTypes(context) {
const schema = context.schema;
const queryType = schema.getQueryType();
if (!queryType) {
context.reportError(`Query root type must be provided.`, schema.astNode);
} else if (!isObjectType(queryType)) {
context.reportError(
`Query root type must be Object type, it cannot be ${String(queryType)}.`,
getOperationTypeNode(schema, queryType, 'query'),
);
}
const mutationType = schema.getMutationType();
if (mutationType && !isObjectType(mutationType)) {
context.reportError(
'Mutation root type must be Object type if provided, it cannot be ' +
`${String(mutationType)}.`,
getOperationTypeNode(schema, mutationType, 'mutation'),
);
}
const subscriptionType = schema.getSubscriptionType();
if (subscriptionType && !isObjectType(subscriptionType)) {
context.reportError(
'Subscription root type must be Object type if provided, it cannot be ' +
`${String(subscriptionType)}.`,
getOperationTypeNode(schema, subscriptionType, 'subscription'),
);
}
}
function getOperationTypeNode(
schema: GraphQLSchema,
type: GraphQLObjectType,
operation: string,
): ?ASTNode {
for (const node of getAllNodes(schema)) {
if (node.operationTypes) {
for (const operationType of node.operationTypes) {
if (operationType.operation === operation) {
return operationType.type;
}
}
}
}
return type.astNode;
}
function validateDirectives(context: SchemaValidationContext): void {
const directives = context.schema.getDirectives();
directives.forEach(directive => {
// Ensure all directives are in fact GraphQL directives.
if (!isDirective(directive)) {
context.reportError(
`Expected directive but got: ${String(directive)}.`,
directive && directive.astNode,
);
return;
}
// Ensure they are named correctly.
validateName(context, directive);
// TODO: Ensure proper locations.
// Ensure the arguments are valid.
const argNames = Object.create(null);
directive.args.forEach(arg => {
const argName = arg.name;
// Ensure they are named correctly.
validateName(context, arg);
// Ensure they are unique per directive.
if (argNames[argName]) {
context.reportError(
`Argument @${directive.name}(${argName}:) can only be defined once.`,
getAllDirectiveArgNodes(directive, argName),
);
return; // continue loop
}
argNames[argName] = true;
// Ensure the type is an input type.
if (!isInputType(arg.type)) {
context.reportError(
`The type of @${directive.name}(${argName}:) must be Input Type ` +
`but got: ${String(arg.type)}.`,
getDirectiveArgTypeNode(directive, argName),
);
}
});
});
}
function validateName(
context: SchemaValidationContext,
node: { +name: string, +astNode: ?ASTNode },
): void {
// If a schema explicitly allows some legacy name which is no longer valid,
// allow it to be assumed valid.
if (
context.schema.__allowedLegacyNames &&
context.schema.__allowedLegacyNames.indexOf(node.name) !== -1
) {
return;
}
// Ensure names are valid, however introspection types opt out.
const error = isValidNameError(node.name, node.astNode || undefined);
if (error) {
context.addError(error);
}
}
function validateTypes(context: SchemaValidationContext): void {
const typeMap = context.schema.getTypeMap();
objectValues(typeMap).forEach(type => {
// Ensure all provided types are in fact GraphQL type.
if (!isNamedType(type)) {
context.reportError(
`Expected GraphQL named type but got: ${String(type)}.`,
type && type.astNode,
);
return;
}
// Ensure it is named correctly (excluding introspection types).
if (!isIntrospectionType(type)) {
validateName(context, type);
}
if (isObjectType(type)) {
// Ensure fields are valid
validateFields(context, type);
// Ensure objects implement the interfaces they claim to.
validateObjectInterfaces(context, type);
} else if (isInterfaceType(type)) {
// Ensure fields are valid.
validateFields(context, type);
// Ensure Interfaces include at least 1 Object type.
validateInterfaces(context, type);
} else if (isUnionType(type)) {
// Ensure Unions include valid member types.
validateUnionMembers(context, type);
} else if (isEnumType(type)) {
// Ensure Enums have valid values.
validateEnumValues(context, type);
} else if (isInputObjectType(type)) {
// Ensure Input Object fields are valid.
validateInputFields(context, type);
}
});
}
function validateFields(
context: SchemaValidationContext,
type: GraphQLObjectType | GraphQLInterfaceType,
): void {
const fields = objectValues(type.getFields());
// Objects and Interfaces both must define one or more fields.
if (fields.length === 0) {
context.reportError(
`Type ${type.name} must define one or more fields.`,
getAllNodes(type),
);
}
fields.forEach(field => {
// Ensure they are named correctly.
validateName(context, field);
// Ensure they were defined at most once.
const fieldNodes = getAllFieldNodes(type, field.name);
if (fieldNodes.length > 1) {
context.reportError(
`Field ${type.name}.${field.name} can only be defined once.`,
fieldNodes,
);
return; // continue loop
}
// Ensure the type is an output type
if (!isOutputType(field.type)) {
context.reportError(
`The type of ${type.name}.${field.name} must be Output Type ` +
`but got: ${String(field.type)}.`,
getFieldTypeNode(type, field.name),
);
}
// Ensure the arguments are valid
const argNames = Object.create(null);
field.args.forEach(arg => {
const argName = arg.name;
// Ensure they are named correctly.
validateName(context, arg);
// Ensure they are unique per field.
if (argNames[argName]) {
context.reportError(
`Field argument ${type.name}.${field.name}(${argName}:) can only ` +
'be defined once.',
getAllFieldArgNodes(type, field.name, argName),
);
}
argNames[argName] = true;
// Ensure the type is an input type
if (!isInputType(arg.type)) {
context.reportError(
`The type of ${type.name}.${field.name}(${argName}:) must be Input ` +
`Type but got: ${String(arg.type)}.`,
getFieldArgTypeNode(type, field.name, argName),
);
}
});
});
}
function validateObjectInterfaces(
context: SchemaValidationContext,
object: GraphQLObjectType,
): void {
const implementedTypeNames = Object.create(null);
object.getInterfaces().forEach(iface => {
if (!isInterfaceType(iface)) {
context.reportError(
`Type ${String(object)} must only implement Interface types, ` +
`it cannot implement ${String(iface)}.`,
getImplementsInterfaceNode(object, iface),
);
return;
}
if (implementedTypeNames[iface.name]) {
context.reportError(
`Type ${object.name} can only implement ${iface.name} once.`,
getAllImplementsInterfaceNodes(object, iface),
);
return; // continue loop
}
implementedTypeNames[iface.name] = true;
validateObjectImplementsInterface(context, object, iface);
});
}
function validateInterfaces(
context: SchemaValidationContext,
iface: GraphQLInterfaceType,
): void {
const possibleTypes = context.schema.getPossibleTypes(iface);
if (possibleTypes.length === 0) {
context.reportError(
`Interface ${iface.name} must be implemented ` +
`by at least one Object type.`,
iface.astNode,
);
}
}
function validateObjectImplementsInterface(
context: SchemaValidationContext,
object: GraphQLObjectType,
iface: GraphQLInterfaceType,
): void {
const objectFieldMap = object.getFields();
const ifaceFieldMap = iface.getFields();
// Assert each interface field is implemented.
Object.keys(ifaceFieldMap).forEach(fieldName => {
const objectField = objectFieldMap[fieldName];
const ifaceField = ifaceFieldMap[fieldName];
// Assert interface field exists on object.
if (!objectField) {
context.reportError(
`Interface field ${iface.name}.${fieldName} expected but ` +
`${object.name} does not provide it.`,
[getFieldNode(iface, fieldName), object.astNode],
);
// Continue loop over fields.
return;
}
// Assert interface field type is satisfied by object field type, by being
// a valid subtype. (covariant)
if (!isTypeSubTypeOf(context.schema, objectField.type, ifaceField.type)) {
context.reportError(
`Interface field ${iface.name}.${fieldName} expects type ` +
`${String(ifaceField.type)} but ${object.name}.${fieldName} ` +
`is type ${String(objectField.type)}.`,
[
getFieldTypeNode(iface, fieldName),
getFieldTypeNode(object, fieldName),
],
);
}
// Assert each interface field arg is implemented.
ifaceField.args.forEach(ifaceArg => {
const argName = ifaceArg.name;
const objectArg = find(objectField.args, arg => arg.name === argName);
// Assert interface field arg exists on object field.
if (!objectArg) {
context.reportError(
`Interface field argument ${iface.name}.${fieldName}(${argName}:) ` +
`expected but ${object.name}.${fieldName} does not provide it.`,
[
getFieldArgNode(iface, fieldName, argName),
getFieldNode(object, fieldName),
],
);
// Continue loop over arguments.
return;
}
// Assert interface field arg type matches object field arg type.
// (invariant)
// TODO: change to contravariant?
if (!isEqualType(ifaceArg.type, objectArg.type)) {
context.reportError(
`Interface field argument ${iface.name}.${fieldName}(${argName}:) ` +
`expects type ${String(ifaceArg.type)} but ` +
`${object.name}.${fieldName}(${argName}:) is type ` +
`${String(objectArg.type)}.`,
[
getFieldArgTypeNode(iface, fieldName, argName),
getFieldArgTypeNode(object, fieldName, argName),
],
);
}
// TODO: validate default values?
});
// Assert additional arguments must not be required.
objectField.args.forEach(objectArg => {
const argName = objectArg.name;
const ifaceArg = find(ifaceField.args, arg => arg.name === argName);
if (!ifaceArg && isNonNullType(objectArg.type)) {
context.reportError(
`Object field argument ${object.name}.${fieldName}(${argName}:) ` +
`is of required type ${String(objectArg.type)} but is not also ` +
`provided by the Interface field ${iface.name}.${fieldName}.`,
[
getFieldArgTypeNode(object, fieldName, argName),
getFieldNode(iface, fieldName),
],
);
}
});
});
}
function validateUnionMembers(
context: SchemaValidationContext,
union: GraphQLUnionType,
): void {
const memberTypes = union.getTypes();
if (memberTypes.length === 0) {
context.reportError(
`Union type ${union.name} must define one or more member types.`,
union.astNode,
);
}
const includedTypeNames = Object.create(null);
memberTypes.forEach(memberType => {
if (includedTypeNames[memberType.name]) {
context.reportError(
`Union type ${union.name} can only include type ` +
`${memberType.name} once.`,
getUnionMemberTypeNodes(union, memberType.name),
);
return; // continue loop
}
includedTypeNames[memberType.name] = true;
if (!isObjectType(memberType)) {
context.reportError(
`Union type ${union.name} can only include Object types, ` +
`it cannot include ${String(memberType)}.`,
getUnionMemberTypeNodes(union, String(memberType)),
);
}
});
}
function validateEnumValues(
context: SchemaValidationContext,
enumType: GraphQLEnumType,
): void {
const enumValues = enumType.getValues();
if (enumValues.length === 0) {
context.reportError(
`Enum type ${enumType.name} must define one or more values.`,
enumType.astNode,
);
}
enumValues.forEach(enumValue => {
const valueName = enumValue.name;
// Ensure no duplicates.
const allNodes = getEnumValueNodes(enumType, valueName);
if (allNodes && allNodes.length > 1) {
context.reportError(
`Enum type ${enumType.name} can include value ${valueName} only once.`,
allNodes,
);
}
// Ensure valid name.
validateName(context, enumValue);
if (valueName === 'true' || valueName === 'false' || valueName === 'null') {
context.reportError(
`Enum type ${enumType.name} cannot include value: ${valueName}.`,
enumValue.astNode,
);
}
});
}
function validateInputFields(
context: SchemaValidationContext,
inputObj: GraphQLInputObjectType,
): void {
const fields = objectValues(inputObj.getFields());
if (fields.length === 0) {
context.reportError(
`Input Object type ${inputObj.name} must define one or more fields.`,
inputObj.astNode,
);
}
// Ensure the arguments are valid
fields.forEach(field => {
// Ensure they are named correctly.
validateName(context, field);
// TODO: Ensure they are unique per field.
// Ensure the type is an input type
if (!isInputType(field.type)) {
context.reportError(
`The type of ${inputObj.name}.${field.name} must be Input Type ` +
`but got: ${String(field.type)}.`,
field.astNode && field.astNode.type,
);
}
});
}
function getAllNodes<T: ASTNode, K: ASTNode>(object: {
+astNode: ?T,
+extensionASTNodes?: ?$ReadOnlyArray<K>,
}): $ReadOnlyArray<T | K> {
const { astNode, extensionASTNodes } = object;
return astNode
? extensionASTNodes
? [astNode].concat(extensionASTNodes)
: [astNode]
: extensionASTNodes || [];
}
function getImplementsInterfaceNode(
type: GraphQLObjectType,
iface: GraphQLInterfaceType,
): ?NamedTypeNode {
return getAllImplementsInterfaceNodes(type, iface)[0];
}
function getAllImplementsInterfaceNodes(
type: GraphQLObjectType,
iface: GraphQLInterfaceType,
): $ReadOnlyArray<NamedTypeNode> {
const implementsNodes = [];
const astNodes = getAllNodes(type);
for (let i = 0; i < astNodes.length; i++) {
const astNode = astNodes[i];
if (astNode && astNode.interfaces) {
astNode.interfaces.forEach(node => {
if (node.name.value === iface.name) {
implementsNodes.push(node);
}
});
}
}
return implementsNodes;
}
function getFieldNode(
type: GraphQLObjectType | GraphQLInterfaceType,
fieldName: string,
): ?FieldDefinitionNode {
return getAllFieldNodes(type, fieldName)[0];
}
function getAllFieldNodes(
type: GraphQLObjectType | GraphQLInterfaceType,
fieldName: string,
): $ReadOnlyArray<FieldDefinitionNode> {
const fieldNodes = [];
const astNodes = getAllNodes(type);
for (let i = 0; i < astNodes.length; i++) {
const astNode = astNodes[i];
if (astNode && astNode.fields) {
astNode.fields.forEach(node => {
if (node.name.value === fieldName) {
fieldNodes.push(node);
}
});
}
}
return fieldNodes;
}
function getFieldTypeNode(
type: GraphQLObjectType | GraphQLInterfaceType,
fieldName: string,
): ?TypeNode {
const fieldNode = getFieldNode(type, fieldName);
return fieldNode && fieldNode.type;
}
function getFieldArgNode(
type: GraphQLObjectType | GraphQLInterfaceType,
fieldName: string,
argName: string,
): ?InputValueDefinitionNode {
return getAllFieldArgNodes(type, fieldName, argName)[0];
}
function getAllFieldArgNodes(
type: GraphQLObjectType | GraphQLInterfaceType,
fieldName: string,
argName: string,
): $ReadOnlyArray<InputValueDefinitionNode> {
const argNodes = [];
const fieldNode = getFieldNode(type, fieldName);
if (fieldNode && fieldNode.arguments) {
fieldNode.arguments.forEach(node => {
if (node.name.value === argName) {
argNodes.push(node);
}
});
}
return argNodes;
}
function getFieldArgTypeNode(
type: GraphQLObjectType | GraphQLInterfaceType,
fieldName: string,
argName: string,
): ?TypeNode {
const fieldArgNode = getFieldArgNode(type, fieldName, argName);
return fieldArgNode && fieldArgNode.type;
}
function getAllDirectiveArgNodes(
directive: GraphQLDirective,
argName: string,
): $ReadOnlyArray<InputValueDefinitionNode> {
const argNodes = [];
const directiveNode = directive.astNode;
if (directiveNode && directiveNode.arguments) {
directiveNode.arguments.forEach(node => {
if (node.name.value === argName) {
argNodes.push(node);
}
});
}
return argNodes;
}
function getDirectiveArgTypeNode(
directive: GraphQLDirective,
argName: string,
): ?TypeNode {
const argNode = getAllDirectiveArgNodes(directive, argName)[0];
return argNode && argNode.type;
}
function getUnionMemberTypeNodes(
union: GraphQLUnionType,
typeName: string,
): ?$ReadOnlyArray<NamedTypeNode> {
return (
union.astNode &&
union.astNode.types &&
union.astNode.types.filter(type => type.name.value === typeName)
);
}
function getEnumValueNodes(
enumType: GraphQLEnumType,
valueName: string,
): ?$ReadOnlyArray<EnumValueDefinitionNode> {
return (
enumType.astNode &&
enumType.astNode.values &&
enumType.astNode.values.filter(value => value.name.value === valueName)
);
}