-
Notifications
You must be signed in to change notification settings - Fork 2k
/
schema.ts
462 lines (416 loc) · 14.2 KB
/
schema.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 { inspect } from '../jsutils/inspect.js';
import { instanceOf } from '../jsutils/instanceOf.js';
import type { Maybe } from '../jsutils/Maybe.js';
import type { ObjMap } from '../jsutils/ObjMap.js';
import { toObjMapWithSymbols } from '../jsutils/toObjMap.js';
import type { GraphQLError } from '../error/GraphQLError.js';
import type {
SchemaDefinitionNode,
SchemaExtensionNode,
} from '../language/ast.js';
import { OperationTypeNode } from '../language/ast.js';
import type {
GraphQLAbstractType,
GraphQLCompositeType,
GraphQLField,
GraphQLInterfaceType,
GraphQLNamedType,
GraphQLObjectType,
GraphQLType,
} from './definition.js';
import {
getNamedType,
isInputObjectType,
isInterfaceType,
isObjectType,
isUnionType,
} from './definition.js';
import type { GraphQLDirective } from './directives.js';
import { isDirective, specifiedDirectives } from './directives.js';
import {
__Schema,
SchemaMetaFieldDef,
TypeMetaFieldDef,
TypeNameMetaFieldDef,
} from './introspection.js';
/**
* Test if the given value is a GraphQL schema.
*/
export function isSchema(schema: unknown): schema is GraphQLSchema {
return instanceOf(schema, GraphQLSchema);
}
export function assertSchema(schema: unknown): GraphQLSchema {
if (!isSchema(schema)) {
throw new Error(`Expected ${inspect(schema)} to be a GraphQL schema.`);
}
return schema;
}
/**
* Custom extensions
*
* @remarks
* Use a unique identifier name for your extension, for example the name of
* your library or project. Do not use a shortened identifier as this increases
* the risk of conflicts. We recommend you add at most one extension field,
* an object which can contain all the values you need.
*/
export interface GraphQLSchemaExtensions {
[attributeName: string | symbol]: unknown;
}
/**
* Schema Definition
*
* A Schema is created by supplying the root types of each type of operation,
* query and mutation (optional). A schema definition is then supplied to the
* validator and executor.
*
* Example:
*
* ```ts
* const MyAppSchema = new GraphQLSchema({
* query: MyAppQueryRootType,
* mutation: MyAppMutationRootType,
* })
* ```
*
* Note: When the schema is constructed, by default only the types that are
* reachable by traversing the root types are included, other types must be
* explicitly referenced.
*
* Example:
*
* ```ts
* const characterInterface = new GraphQLInterfaceType({
* name: 'Character',
* ...
* });
*
* const humanType = new GraphQLObjectType({
* name: 'Human',
* interfaces: [characterInterface],
* ...
* });
*
* const droidType = new GraphQLObjectType({
* name: 'Droid',
* interfaces: [characterInterface],
* ...
* });
*
* const schema = new GraphQLSchema({
* query: new GraphQLObjectType({
* name: 'Query',
* fields: {
* hero: { type: characterInterface, ... },
* }
* }),
* ...
* // Since this schema references only the `Character` interface it's
* // necessary to explicitly list the types that implement it if
* // you want them to be included in the final schema.
* types: [humanType, droidType],
* })
* ```
*
* Note: If an array of `directives` are provided to GraphQLSchema, that will be
* the exact list of directives represented and allowed. If `directives` is not
* provided then a default set of the specified directives (e.g. `@include` and
* `@skip`) will be used. If you wish to provide *additional* directives to these
* specified directives, you must explicitly declare them. Example:
*
* ```ts
* const MyAppSchema = new GraphQLSchema({
* ...
* directives: specifiedDirectives.concat([ myCustomDirective ]),
* })
* ```
*/
export class GraphQLSchema {
description: Maybe<string>;
extensions: Readonly<GraphQLSchemaExtensions>;
astNode: Maybe<SchemaDefinitionNode>;
extensionASTNodes: ReadonlyArray<SchemaExtensionNode>;
assumeValid: boolean;
__validationErrors: Maybe<ReadonlyArray<GraphQLError>>;
private _queryType: Maybe<GraphQLObjectType>;
private _mutationType: Maybe<GraphQLObjectType>;
private _subscriptionType: Maybe<GraphQLObjectType>;
private _directives: ReadonlyArray<GraphQLDirective>;
private _typeMap: TypeMap;
private _subTypeMap: Map<
GraphQLAbstractType,
Set<GraphQLObjectType | GraphQLInterfaceType>
>;
private _implementationsMap: ObjMap<{
objects: Array<GraphQLObjectType>;
interfaces: Array<GraphQLInterfaceType>;
}>;
constructor(config: Readonly<GraphQLSchemaConfig>) {
// If this schema was built from a source known to be valid, then it may be
// marked with assumeValid to avoid an additional type system validation.
this.assumeValid = config.assumeValid ?? false;
// Used as a cache for validateSchema().
this.__validationErrors = config.assumeValid === true ? [] : undefined;
this.description = config.description;
this.extensions = toObjMapWithSymbols(config.extensions);
this.astNode = config.astNode;
this.extensionASTNodes = config.extensionASTNodes ?? [];
this._queryType = config.query;
this._mutationType = config.mutation;
this._subscriptionType = config.subscription;
// Provide specified directives (e.g. @include and @skip) by default.
this._directives = config.directives ?? specifiedDirectives;
// To preserve order of user-provided types, we add first to add them to
// the set of "collected" types, so `collectReferencedTypes` ignore them.
const allReferencedTypes = new Set<GraphQLNamedType>(config.types);
if (config.types != null) {
for (const type of config.types) {
// When we ready to process this type, we remove it from "collected" types
// and then add it together with all dependent types in the correct position.
allReferencedTypes.delete(type);
collectReferencedTypes(type, allReferencedTypes);
}
}
if (this._queryType != null) {
collectReferencedTypes(this._queryType, allReferencedTypes);
}
if (this._mutationType != null) {
collectReferencedTypes(this._mutationType, allReferencedTypes);
}
if (this._subscriptionType != null) {
collectReferencedTypes(this._subscriptionType, allReferencedTypes);
}
for (const directive of this._directives) {
// Directives are not validated until validateSchema() is called.
if (isDirective(directive)) {
for (const arg of directive.args) {
collectReferencedTypes(arg.type, allReferencedTypes);
}
}
}
collectReferencedTypes(__Schema, allReferencedTypes);
// Storing the resulting map for reference by the schema.
this._typeMap = Object.create(null);
this._subTypeMap = new Map();
// Keep track of all implementations by interface name.
this._implementationsMap = Object.create(null);
for (const namedType of allReferencedTypes) {
if (namedType == null) {
continue;
}
const typeName = namedType.name;
if (this._typeMap[typeName] !== undefined) {
throw new Error(
`Schema must contain uniquely named types but contains multiple types named "${typeName}".`,
);
}
this._typeMap[typeName] = namedType;
if (isInterfaceType(namedType)) {
// Store implementations by interface.
for (const iface of namedType.getInterfaces()) {
if (isInterfaceType(iface)) {
let implementations = this._implementationsMap[iface.name];
if (implementations === undefined) {
implementations = this._implementationsMap[iface.name] = {
objects: [],
interfaces: [],
};
}
implementations.interfaces.push(namedType);
}
}
} else if (isObjectType(namedType)) {
// Store implementations by objects.
for (const iface of namedType.getInterfaces()) {
if (isInterfaceType(iface)) {
let implementations = this._implementationsMap[iface.name];
if (implementations === undefined) {
implementations = this._implementationsMap[iface.name] = {
objects: [],
interfaces: [],
};
}
implementations.objects.push(namedType);
}
}
}
}
}
get [Symbol.toStringTag]() {
return 'GraphQLSchema';
}
getQueryType(): Maybe<GraphQLObjectType> {
return this._queryType;
}
getMutationType(): Maybe<GraphQLObjectType> {
return this._mutationType;
}
getSubscriptionType(): Maybe<GraphQLObjectType> {
return this._subscriptionType;
}
getRootType(operation: OperationTypeNode): Maybe<GraphQLObjectType> {
switch (operation) {
case OperationTypeNode.QUERY:
return this.getQueryType();
case OperationTypeNode.MUTATION:
return this.getMutationType();
case OperationTypeNode.SUBSCRIPTION:
return this.getSubscriptionType();
}
}
getTypeMap(): TypeMap {
return this._typeMap;
}
getType(name: string): GraphQLNamedType | undefined {
return this.getTypeMap()[name];
}
getPossibleTypes(
abstractType: GraphQLAbstractType,
): ReadonlyArray<GraphQLObjectType> {
return isUnionType(abstractType)
? abstractType.getTypes()
: this.getImplementations(abstractType).objects;
}
getImplementations(interfaceType: GraphQLInterfaceType): {
objects: ReadonlyArray<GraphQLObjectType>;
interfaces: ReadonlyArray<GraphQLInterfaceType>;
} {
const implementations = this._implementationsMap[interfaceType.name];
return implementations ?? { objects: [], interfaces: [] };
}
isSubType(
abstractType: GraphQLAbstractType,
maybeSubType: GraphQLObjectType | GraphQLInterfaceType,
): boolean {
let set = this._subTypeMap.get(abstractType);
if (set === undefined) {
if (isUnionType(abstractType)) {
set = new Set<GraphQLObjectType>(abstractType.getTypes());
} else {
const implementations = this.getImplementations(abstractType);
set = new Set<GraphQLObjectType | GraphQLInterfaceType>([
...implementations.objects,
...implementations.interfaces,
]);
}
this._subTypeMap.set(abstractType, set);
}
return set.has(maybeSubType);
}
getDirectives(): ReadonlyArray<GraphQLDirective> {
return this._directives;
}
getDirective(name: string): Maybe<GraphQLDirective> {
return this.getDirectives().find((directive) => directive.name === name);
}
/**
* This method looks up the field on the given type definition.
* It has special casing for the three introspection fields, `__schema`,
* `__type` and `__typename`.
*
* `__typename` is special because it can always be queried as a field, even
* in situations where no other fields are allowed, like on a Union.
*
* `__schema` and `__type` could get automatically added to the query type,
* but that would require mutating type definitions, which would cause issues.
*/
getField(
parentType: GraphQLCompositeType,
fieldName: string,
): GraphQLField<unknown, unknown> | undefined {
switch (fieldName) {
case SchemaMetaFieldDef.name:
return this.getQueryType() === parentType
? SchemaMetaFieldDef
: undefined;
case TypeMetaFieldDef.name:
return this.getQueryType() === parentType
? TypeMetaFieldDef
: undefined;
case TypeNameMetaFieldDef.name:
return TypeNameMetaFieldDef;
}
// this function is part "hot" path inside executor and check presence
// of 'getFields' is faster than to use `!isUnionType`
if ('getFields' in parentType) {
return parentType.getFields()[fieldName];
}
return undefined;
}
toConfig(): GraphQLSchemaNormalizedConfig {
return {
description: this.description,
query: this.getQueryType(),
mutation: this.getMutationType(),
subscription: this.getSubscriptionType(),
types: Object.values(this.getTypeMap()),
directives: this.getDirectives(),
extensions: this.extensions,
astNode: this.astNode,
extensionASTNodes: this.extensionASTNodes,
assumeValid: this.assumeValid,
};
}
}
type TypeMap = ObjMap<GraphQLNamedType>;
export interface GraphQLSchemaValidationOptions {
/**
* When building a schema from a GraphQL service's introspection result, it
* might be safe to assume the schema is valid. Set to true to assume the
* produced schema is valid.
*
* Default: false
*/
assumeValid?: boolean | undefined;
}
export interface GraphQLSchemaConfig extends GraphQLSchemaValidationOptions {
description?: Maybe<string>;
query?: Maybe<GraphQLObjectType>;
mutation?: Maybe<GraphQLObjectType>;
subscription?: Maybe<GraphQLObjectType>;
types?: Maybe<ReadonlyArray<GraphQLNamedType>>;
directives?: Maybe<ReadonlyArray<GraphQLDirective>>;
extensions?: Maybe<Readonly<GraphQLSchemaExtensions>>;
astNode?: Maybe<SchemaDefinitionNode>;
extensionASTNodes?: Maybe<ReadonlyArray<SchemaExtensionNode>>;
}
/**
* @internal
*/
export interface GraphQLSchemaNormalizedConfig extends GraphQLSchemaConfig {
description: Maybe<string>;
types: ReadonlyArray<GraphQLNamedType>;
directives: ReadonlyArray<GraphQLDirective>;
extensions: Readonly<GraphQLSchemaExtensions>;
extensionASTNodes: ReadonlyArray<SchemaExtensionNode>;
assumeValid: boolean;
}
function collectReferencedTypes(
type: GraphQLType,
typeSet: Set<GraphQLNamedType>,
): Set<GraphQLNamedType> {
const namedType = getNamedType(type);
if (!typeSet.has(namedType)) {
typeSet.add(namedType);
if (isUnionType(namedType)) {
for (const memberType of namedType.getTypes()) {
collectReferencedTypes(memberType, typeSet);
}
} else if (isObjectType(namedType) || isInterfaceType(namedType)) {
for (const interfaceType of namedType.getInterfaces()) {
collectReferencedTypes(interfaceType, typeSet);
}
for (const field of Object.values(namedType.getFields())) {
collectReferencedTypes(field.type, typeSet);
for (const arg of field.args) {
collectReferencedTypes(arg.type, typeSet);
}
}
} else if (isInputObjectType(namedType)) {
for (const field of Object.values(namedType.getFields())) {
collectReferencedTypes(field.type, typeSet);
}
}
}
return typeSet;
}