-
Notifications
You must be signed in to change notification settings - Fork 470
/
Copy pathbuildSchemaFromSDL.ts
333 lines (287 loc) · 9.57 KB
/
buildSchemaFromSDL.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
import {
concatAST,
DocumentNode,
extendSchema,
GraphQLSchema,
isObjectType,
isTypeDefinitionNode,
isTypeExtensionNode,
Kind,
TypeDefinitionNode,
TypeExtensionNode,
DirectiveDefinitionNode,
SchemaDefinitionNode,
SchemaExtensionNode,
OperationTypeNode,
GraphQLObjectType,
GraphQLEnumType,
isAbstractType,
isScalarType,
isEnumType,
GraphQLEnumValueConfig,
DirectiveNode,
} from "graphql";
import { validateSDL } from "graphql/validation/validate";
import { isDocumentNode, isNode } from "../utilities/graphql";
import { GraphQLResolverMap } from "./resolverMap";
import { GraphQLSchemaValidationError } from "./GraphQLSchemaValidationError";
import { specifiedSDLRules } from "graphql/validation/specifiedRules";
// TODO(Node.js 10): When we deprecate Node.js 10, remove this and switch
// to using `Array.prototype.flat`. When doing this, deleting the hand-rolled
// types in `./packages/apollo-gateway/src/types/` that go with it.
import flat from "core-js-pure/features/array/flat";
import {
KnownTypeNamesRule,
UniqueDirectivesPerLocationRule,
ValidationRule,
} from "graphql/validation";
import { mapValues } from "../utilities/mapValues";
export interface GraphQLSchemaModule {
typeDefs: DocumentNode;
resolvers?: GraphQLResolverMap<any>;
}
const skippedSDLRules: ValidationRule[] = [
KnownTypeNamesRule,
UniqueDirectivesPerLocationRule,
];
// BREAKING VERSION: Remove this when graphql-js 15 is minimum version.
// Currently, this PossibleTypeExtensions rule is experimental and thus not
// exposed directly from the rules module above. This may change in the future!
// Additionally, it does not exist in prior graphql versions. Thus this try/catch.
try {
const PossibleTypeExtensions: typeof import("graphql/validation/rules/PossibleTypeExtensions").PossibleTypeExtensions =
require("graphql/validation/rules/PossibleTypeExtensions").PossibleTypeExtensions;
if (PossibleTypeExtensions) {
skippedSDLRules.push(PossibleTypeExtensions);
}
} catch (e) {
// No need to fail in this case. Instead, if this validation rule is missing, we will assume its not used
// by the version of `graphql` that is available to us.
}
// BREAKING AGAIN: PossibleTypeExtensions is finalized into PossibleTypeExtensionsRule in
// graphql 16. For compatible reason, try catch logic for 15 is kept with extra logic for 16.
try {
// Compatible for graphql-js@16
const PossibleTypeExtensionsRule =
require("graphql").PossibleTypeExtensionsRule;
if (PossibleTypeExtensionsRule) {
skippedSDLRules.push(PossibleTypeExtensionsRule);
}
} catch (e) {
// No need to fail in this case. Instead, if this validation rule is missing, we will assume its not used
// by the version of `graphql` that is available to us.
}
const sdlRules = specifiedSDLRules.filter(
(rule) => !skippedSDLRules.includes(rule)
);
export function modulesFromSDL(
modulesOrSDL: (GraphQLSchemaModule | DocumentNode)[] | DocumentNode
): GraphQLSchemaModule[] {
if (Array.isArray(modulesOrSDL)) {
return modulesOrSDL.map((moduleOrSDL) => {
if (isNode(moduleOrSDL) && isDocumentNode(moduleOrSDL)) {
return { typeDefs: moduleOrSDL };
} else {
return moduleOrSDL;
}
});
} else {
return [{ typeDefs: modulesOrSDL }];
}
}
export function buildSchemaFromSDL(
modulesOrSDL: (GraphQLSchemaModule | DocumentNode)[] | DocumentNode,
schemaToExtend?: GraphQLSchema
): GraphQLSchema {
const modules = modulesFromSDL(modulesOrSDL);
const documentAST = concatAST(modules.map((module) => module.typeDefs));
const errors = validateSDL(documentAST, schemaToExtend, sdlRules);
if (errors.length > 0) {
throw new GraphQLSchemaValidationError(errors);
}
const definitionsMap: {
[name: string]: TypeDefinitionNode[];
} = Object.create(null);
const extensionsMap: {
[name: string]: TypeExtensionNode[];
} = Object.create(null);
const directiveDefinitions: DirectiveDefinitionNode[] = [];
const schemaDefinitions: SchemaDefinitionNode[] = [];
const schemaExtensions: SchemaExtensionNode[] = [];
const schemaDirectives: DirectiveNode[] = [];
for (const definition of documentAST.definitions) {
if (isTypeDefinitionNode(definition)) {
const typeName = definition.name.value;
if (definitionsMap[typeName]) {
definitionsMap[typeName].push(definition);
} else {
definitionsMap[typeName] = [definition];
}
} else if (isTypeExtensionNode(definition)) {
const typeName = definition.name.value;
if (extensionsMap[typeName]) {
extensionsMap[typeName].push(definition);
} else {
extensionsMap[typeName] = [definition];
}
} else if (definition.kind === Kind.DIRECTIVE_DEFINITION) {
directiveDefinitions.push(definition);
} else if (definition.kind === Kind.SCHEMA_DEFINITION) {
schemaDefinitions.push(definition);
schemaDirectives.push(
...(definition.directives ? definition.directives : [])
);
} else if (definition.kind === Kind.SCHEMA_EXTENSION) {
schemaExtensions.push(definition);
}
}
let schema = schemaToExtend
? schemaToExtend
: new GraphQLSchema({
query: undefined,
});
const missingTypeDefinitions: TypeDefinitionNode[] = [];
for (const [extendedTypeName, extensions] of Object.entries(extensionsMap)) {
if (!definitionsMap[extendedTypeName]) {
const extension = extensions[0];
const kind = extension.kind;
const definition = {
kind: extKindToDefKind[kind],
name: extension.name,
} as TypeDefinitionNode;
missingTypeDefinitions.push(definition);
}
}
schema = extendSchema(
schema,
{
kind: Kind.DOCUMENT,
definitions: [
...flat(Object.values(definitionsMap)),
...missingTypeDefinitions,
...directiveDefinitions,
],
},
{
assumeValidSDL: true,
}
);
schema = extendSchema(
schema,
{
kind: Kind.DOCUMENT,
definitions: flat(Object.values(extensionsMap)),
},
{
assumeValidSDL: true,
}
);
let operationTypeMap: { [operation in OperationTypeNode]?: string };
if (schemaDefinitions.length > 0 || schemaExtensions.length > 0) {
operationTypeMap = {};
const operationTypes = flat(
[...schemaDefinitions, ...schemaExtensions]
.map((node) => node.operationTypes)
.filter(isNotNullOrUndefined)
);
for (const { operation, type } of operationTypes) {
operationTypeMap[operation] = type.name.value;
}
} else {
operationTypeMap = {
query: "Query",
mutation: "Mutation",
subscription: "Subscription",
};
}
schema = new GraphQLSchema({
...schema.toConfig(),
...mapValues(operationTypeMap, (typeName) =>
typeName
? (schema.getType(typeName) as GraphQLObjectType<any, any>)
: undefined
),
astNode: {
kind: Kind.SCHEMA_DEFINITION,
directives: schemaDirectives,
operationTypes: [], // satisfies typescript, will be ignored
},
});
for (const module of modules) {
if (!module.resolvers) continue;
addResolversToSchema(schema, module.resolvers);
}
return schema;
}
const extKindToDefKind = {
[Kind.SCALAR_TYPE_EXTENSION]: Kind.SCALAR_TYPE_DEFINITION,
[Kind.OBJECT_TYPE_EXTENSION]: Kind.OBJECT_TYPE_DEFINITION,
[Kind.INTERFACE_TYPE_EXTENSION]: Kind.INTERFACE_TYPE_DEFINITION,
[Kind.UNION_TYPE_EXTENSION]: Kind.UNION_TYPE_DEFINITION,
[Kind.ENUM_TYPE_EXTENSION]: Kind.ENUM_TYPE_DEFINITION,
[Kind.INPUT_OBJECT_TYPE_EXTENSION]: Kind.INPUT_OBJECT_TYPE_DEFINITION,
};
export function addResolversToSchema(
schema: GraphQLSchema,
resolvers: GraphQLResolverMap<any>
) {
for (const [typeName, fieldConfigs] of Object.entries(resolvers)) {
const type = schema.getType(typeName);
if (isAbstractType(type)) {
for (const [fieldName, fieldConfig] of Object.entries(fieldConfigs)) {
if (fieldName.startsWith("__")) {
(type as any)[fieldName.substring(2)] = fieldConfig;
}
}
}
if (isScalarType(type)) {
for (const fn in fieldConfigs) {
(type as any)[fn] = (fieldConfigs as any)[fn];
}
}
if (isEnumType(type)) {
const values = type.getValues();
const newValues: { [key: string]: GraphQLEnumValueConfig } = {};
values.forEach((value) => {
let newValue = (fieldConfigs as any)[value.name];
if (newValue === undefined) {
newValue = value.name;
}
newValues[value.name] = {
value: newValue,
deprecationReason: value.deprecationReason,
description: value.description,
astNode: value.astNode,
extensions: undefined,
};
});
// In place updating hack to get around pulling in the full
// schema walking and immutable updating machinery from graphql-tools
Object.assign(
type,
new GraphQLEnumType({
...type.toConfig(),
values: newValues,
})
);
}
if (!isObjectType(type)) continue;
const fieldMap = type.getFields();
for (const [fieldName, fieldConfig] of Object.entries(fieldConfigs)) {
if (fieldName.startsWith("__")) {
(type as any)[fieldName.substring(2)] = fieldConfig;
continue;
}
const field = fieldMap[fieldName];
if (!field) continue;
if (typeof fieldConfig === "function") {
field.resolve = fieldConfig;
} else {
field.resolve = fieldConfig.resolve;
}
}
}
}
function isNotNullOrUndefined<T>(value: T | null | undefined): value is T {
return value !== null && typeof value !== "undefined";
}