/
buildASTSchema.js
420 lines (373 loc) · 11.1 KB
/
buildASTSchema.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
/* @flow */
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import find from '../jsutils/find';
import invariant from '../jsutils/invariant';
import keyMap from '../jsutils/keyMap';
import keyValMap from '../jsutils/keyValMap';
import { valueFromAST } from './valueFromAST';
import { getArgumentValues } from '../execution/values';
import {
LIST_TYPE,
NON_NULL_TYPE,
DOCUMENT,
SCHEMA_DEFINITION,
SCALAR_TYPE_DEFINITION,
OBJECT_TYPE_DEFINITION,
INTERFACE_TYPE_DEFINITION,
ENUM_TYPE_DEFINITION,
UNION_TYPE_DEFINITION,
INPUT_OBJECT_TYPE_DEFINITION,
DIRECTIVE_DEFINITION,
} from '../language/kinds';
import type {
Document,
Directive,
Type,
NamedType,
SchemaDefinition,
TypeDefinition,
ScalarTypeDefinition,
ObjectTypeDefinition,
InputValueDefinition,
InterfaceTypeDefinition,
UnionTypeDefinition,
EnumTypeDefinition,
InputObjectTypeDefinition,
DirectiveDefinition,
} from '../language/ast';
import {
GraphQLSchema,
GraphQLScalarType,
GraphQLObjectType,
GraphQLInterfaceType,
GraphQLUnionType,
GraphQLEnumType,
GraphQLInputObjectType,
GraphQLString,
GraphQLInt,
GraphQLFloat,
GraphQLBoolean,
GraphQLID,
GraphQLList,
GraphQLNonNull,
} from '../type';
import {
GraphQLDirective,
GraphQLSkipDirective,
GraphQLIncludeDirective,
GraphQLDeprecatedDirective,
} from '../type/directives';
import {
__Schema,
__Directive,
__DirectiveLocation,
__Type,
__Field,
__InputValue,
__EnumValue,
__TypeKind,
} from '../type/introspection';
import type {
GraphQLType,
GraphQLNamedType
} from '../type/definition';
type CompositeDefinition =
ObjectTypeDefinition |
InterfaceTypeDefinition |
UnionTypeDefinition;
function buildWrappedType(
innerType: GraphQLType,
inputTypeAST: Type
): GraphQLType {
if (inputTypeAST.kind === LIST_TYPE) {
return new GraphQLList(buildWrappedType(innerType, inputTypeAST.type));
}
if (inputTypeAST.kind === NON_NULL_TYPE) {
const wrappedType = buildWrappedType(innerType, inputTypeAST.type);
invariant(!(wrappedType instanceof GraphQLNonNull), 'No nesting nonnull.');
return new GraphQLNonNull(wrappedType);
}
return innerType;
}
function getNamedTypeAST(typeAST: Type): NamedType {
let namedType = typeAST;
while (namedType.kind === LIST_TYPE || namedType.kind === NON_NULL_TYPE) {
namedType = namedType.type;
}
return namedType;
}
/**
* This takes the ast of a schema document produced by the parse function in
* src/language/parser.js.
*
* Given that AST it constructs a GraphQLSchema. As constructed
* they are not particularly useful for non-introspection queries
* since they have no resolve methods.
*/
export function buildASTSchema(ast: Document): GraphQLSchema {
if (!ast || ast.kind !== DOCUMENT) {
throw new Error('Must provide a document ast.');
}
let schemaDef: ?SchemaDefinition;
const typeDefs: Array<TypeDefinition> = [];
const directiveDefs: Array<DirectiveDefinition> = [];
for (let i = 0; i < ast.definitions.length; i++) {
const d = ast.definitions[i];
switch (d.kind) {
case SCHEMA_DEFINITION:
if (schemaDef) {
throw new Error('Must provide only one schema definition.');
}
schemaDef = d;
break;
case SCALAR_TYPE_DEFINITION:
case OBJECT_TYPE_DEFINITION:
case INTERFACE_TYPE_DEFINITION:
case ENUM_TYPE_DEFINITION:
case UNION_TYPE_DEFINITION:
case INPUT_OBJECT_TYPE_DEFINITION:
typeDefs.push(d);
break;
case DIRECTIVE_DEFINITION:
directiveDefs.push(d);
break;
}
}
if (!schemaDef) {
throw new Error('Must provide a schema definition.');
}
let queryTypeName;
let mutationTypeName;
let subscriptionTypeName;
schemaDef.operationTypes.forEach(operationType => {
const typeName = operationType.type.name.value;
if (operationType.operation === 'query') {
if (queryTypeName) {
throw new Error('Must provide only one query type in schema.');
}
queryTypeName = typeName;
} else if (operationType.operation === 'mutation') {
if (mutationTypeName) {
throw new Error('Must provide only one mutation type in schema.');
}
mutationTypeName = typeName;
} else if (operationType.operation === 'subscription') {
if (subscriptionTypeName) {
throw new Error('Must provide only one subscription type in schema.');
}
subscriptionTypeName = typeName;
}
});
if (!queryTypeName) {
throw new Error('Must provide schema definition with query type.');
}
const astMap: {[name: string]: TypeDefinition} =
keyMap(typeDefs, d => d.name.value);
if (!astMap[queryTypeName]) {
throw new Error(
`Specified query type "${queryTypeName}" not found in document.`
);
}
if (mutationTypeName && !astMap[mutationTypeName]) {
throw new Error(
`Specified mutation type "${mutationTypeName}" not found in document.`
);
}
if (subscriptionTypeName && !astMap[subscriptionTypeName]) {
throw new Error(
`Specified subscription type "${
subscriptionTypeName}" not found in document.`
);
}
const innerTypeMap = {
String: GraphQLString,
Int: GraphQLInt,
Float: GraphQLFloat,
Boolean: GraphQLBoolean,
ID: GraphQLID,
__Schema,
__Directive,
__DirectiveLocation,
__Type,
__Field,
__InputValue,
__EnumValue,
__TypeKind,
};
const types = typeDefs.map(def => typeDefNamed(def.name.value));
const directives = directiveDefs.map(getDirective);
// If specified directives were not explicitly declared, add them.
if (!directives.some(directive => directive.name === 'skip')) {
directives.push(GraphQLSkipDirective);
}
if (!directives.some(directive => directive.name === 'include')) {
directives.push(GraphQLIncludeDirective);
}
if (!directives.some(directive => directive.name === 'deprecated')) {
directives.push(GraphQLDeprecatedDirective);
}
return new GraphQLSchema({
query: getObjectType(astMap[queryTypeName]),
mutation: mutationTypeName ? getObjectType(astMap[mutationTypeName]) : null,
subscription:
subscriptionTypeName ? getObjectType(astMap[subscriptionTypeName]) : null,
types,
directives,
});
function getDirective(directiveAST: DirectiveDefinition): GraphQLDirective {
return new GraphQLDirective({
name: directiveAST.name.value,
locations: directiveAST.locations.map(node => node.value),
args: makeInputValues(directiveAST.arguments),
});
}
function getObjectType(typeAST: TypeDefinition): GraphQLObjectType {
const type = typeDefNamed(typeAST.name.value);
invariant(
type instanceof GraphQLObjectType,
'AST must provide object type.'
);
return (type: any);
}
function produceTypeDef(typeAST: Type): GraphQLType {
const typeName = getNamedTypeAST(typeAST).name.value;
const typeDef = typeDefNamed(typeName);
return buildWrappedType(typeDef, typeAST);
}
function typeDefNamed(typeName: string): GraphQLNamedType {
if (innerTypeMap[typeName]) {
return innerTypeMap[typeName];
}
if (!astMap[typeName]) {
throw new Error(`Type "${typeName}" not found in document.`);
}
const innerTypeDef = makeSchemaDef(astMap[typeName]);
if (!innerTypeDef) {
throw new Error(`Nothing constructed for "${typeName}".`);
}
innerTypeMap[typeName] = innerTypeDef;
return innerTypeDef;
}
function makeSchemaDef(def) {
if (!def) {
throw new Error('def must be defined');
}
switch (def.kind) {
case OBJECT_TYPE_DEFINITION:
return makeTypeDef(def);
case INTERFACE_TYPE_DEFINITION:
return makeInterfaceDef(def);
case ENUM_TYPE_DEFINITION:
return makeEnumDef(def);
case UNION_TYPE_DEFINITION:
return makeUnionDef(def);
case SCALAR_TYPE_DEFINITION:
return makeScalarDef(def);
case INPUT_OBJECT_TYPE_DEFINITION:
return makeInputObjectDef(def);
default:
throw new Error(`Type kind "${def.kind}" not supported.`);
}
}
function makeTypeDef(def: ObjectTypeDefinition) {
const typeName = def.name.value;
const config = {
name: typeName,
fields: () => makeFieldDefMap(def),
interfaces: () => makeImplementedInterfaces(def),
};
return new GraphQLObjectType(config);
}
function makeFieldDefMap(def: CompositeDefinition) {
return keyValMap(
def.fields,
field => field.name.value,
field => ({
type: produceTypeDef(field.type),
args: makeInputValues(field.arguments),
deprecationReason: getDeprecationReason(field.directives)
})
);
}
function makeImplementedInterfaces(def: ObjectTypeDefinition) {
return def.interfaces.map(inter => produceTypeDef(inter));
}
function makeInputValues(values: Array<InputValueDefinition>) {
return keyValMap(
values,
value => value.name.value,
value => {
const type = produceTypeDef(value.type);
return { type, defaultValue: valueFromAST(value.defaultValue, type) };
}
);
}
function makeInterfaceDef(def: InterfaceTypeDefinition) {
const typeName = def.name.value;
const config = {
name: typeName,
resolveType: () => null,
fields: () => makeFieldDefMap(def),
};
return new GraphQLInterfaceType(config);
}
function makeEnumDef(def: EnumTypeDefinition) {
const enumType = new GraphQLEnumType({
name: def.name.value,
values: keyValMap(
def.values,
enumValue => enumValue.name.value,
enumValue => ({
deprecationReason: getDeprecationReason(enumValue.directives)
})
),
});
return enumType;
}
function makeUnionDef(def: UnionTypeDefinition) {
return new GraphQLUnionType({
name: def.name.value,
resolveType: () => null,
types: def.types.map(t => produceTypeDef(t)),
});
}
function makeScalarDef(def: ScalarTypeDefinition) {
return new GraphQLScalarType({
name: def.name.value,
serialize: () => null,
// Note: validation calls the parse functions to determine if a
// literal value is correct. Returning null would cause use of custom
// scalars to always fail validation. Returning false causes them to
// always pass validation.
parseValue: () => false,
parseLiteral: () => false,
});
}
function makeInputObjectDef(def: InputObjectTypeDefinition) {
return new GraphQLInputObjectType({
name: def.name.value,
fields: () => makeInputValues(def.fields),
});
}
}
function getDeprecationReason(directives: ?Array<Directive>): ?string {
const deprecatedAST = directives && find(
directives,
directive => directive.name.value === GraphQLDeprecatedDirective.name
);
if (!deprecatedAST) {
return;
}
const { reason } = getArgumentValues(
GraphQLDeprecatedDirective.args,
deprecatedAST.arguments
);
return (reason: any);
}