/
SchemaBuilder.js
570 lines (521 loc) · 17.6 KB
/
SchemaBuilder.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
// @flow
import debugFactory from "debug";
import makeNewBuild from "./makeNewBuild";
import { bindAll } from "./utils";
import * as graphql from "graphql";
import type {
GraphQLType,
GraphQLNamedType,
GraphQLInterfaceType,
GraphQLObjectTypeConfig,
} from "graphql";
import EventEmitter from "events";
// TODO: when we move to TypeScript, change this to:
// import { EventEmitter } from "events";
import type {
simplifyParsedResolveInfoFragmentWithType,
parseResolveInfo,
} from "graphql-parse-resolve-info";
import type { GraphQLResolveInfo } from "graphql/type/definition";
import type resolveNode from "./resolveNode";
import type { FieldWithHooksFunction } from "./makeNewBuild";
const { GraphQLSchema } = graphql;
const debug = debugFactory("graphile-builder");
const INDENT = " ";
export type Options = {
[string]: mixed,
};
export type Plugin = (
builder: SchemaBuilder,
options: Options
) => Promise<void> | void;
type TriggerChangeType = () => void;
export type DataForType = {
[string]: Array<mixed>,
};
export type Build = {|
graphileBuildVersion: string,
graphql: *,
parseResolveInfo: parseResolveInfo,
simplifyParsedResolveInfoFragmentWithType: simplifyParsedResolveInfoFragmentWithType,
// DEPRECATED: getAliasFromResolveInfo: (resolveInfo: GraphQLResolveInfo) => string,
getSafeAliasFromResolveInfo: (resolveInfo: GraphQLResolveInfo) => string,
getSafeAliasFromAlias: (alias: string) => string,
resolveAlias(
data: {},
_args: mixed,
_context: mixed,
resolveInfo: GraphQLResolveInfo
): string,
addType(type: GraphQLNamedType, origin?: ?string): void,
getTypeByName(typeName: string): ?GraphQLType,
extend<Obj1: *, Obj2: *>(base: Obj1, extra: Obj2, hint?: string): Obj1 & Obj2,
newWithHooks<T: GraphQLNamedType | GraphQLSchema, ConfigType: *>(
Class<T>,
spec: ConfigType,
scope: Scope,
performNonEmptyFieldsCheck?: boolean
): ?T,
fieldDataGeneratorsByType: Map<*, *>, // @deprecated - use fieldDataGeneratorsByFieldNameByType instead
fieldDataGeneratorsByFieldNameByType: Map<*, *>,
fieldArgDataGeneratorsByFieldNameByType: Map<*, *>,
inflection: {
// eslint-disable-next-line flowtype/no-weak-types
[string]: (...args: Array<any>) => string,
},
swallowError: (e: Error) => void,
// resolveNode: EXPERIMENTAL, API might change!
resolveNode: resolveNode,
status: {
currentHookName: ?string,
currentHookEvent: ?string,
},
scopeByType: Map<GraphQLType, Scope>,
|};
export type BuildExtensionQuery = {|
$$isQuery: Symbol,
|};
export type Scope = {
__origin: ?string,
[string]: mixed,
};
export type Context = {|
scope: Scope,
type: string,
[string]: mixed,
|};
type DataGeneratorFunction = () => {};
export type ContextGraphQLObjectTypeFields = {|
addDataGeneratorForField: (
fieldName: string,
fn: DataGeneratorFunction
) => void,
recurseDataGeneratorsForField: (fieldName: string) => void, // @deprecated - DO NOT USE!
Self: GraphQLNamedType,
GraphQLObjectType: GraphQLObjectTypeConfig<*, *>,
fieldWithHooks: FieldWithHooksFunction,
|};
type SupportedHookTypes = {} | Build | Array<GraphQLInterfaceType>;
export type Hook<
Type: SupportedHookTypes,
BuildExtensions: *,
ContextExtensions: *
> = {
(
input: Type,
build: { ...Build, ...BuildExtensions },
context: { ...Context, ...ContextExtensions }
): Type,
displayName?: string,
provides?: Array<string>,
before?: Array<string>,
after?: Array<string>,
};
export type WatchUnwatch = (triggerChange: TriggerChangeType) => void;
export type SchemaListener = (newSchema: GraphQLSchema) => void;
class SchemaBuilder extends EventEmitter {
options: Options;
watchers: Array<WatchUnwatch>;
unwatchers: Array<WatchUnwatch>;
triggerChange: ?TriggerChangeType;
depth: number;
hooks: {
[string]: Array<Hook<*, *, *>>,
};
_currentPluginName: ?string;
_generatedSchema: ?GraphQLSchema;
_explicitSchemaListener: ?SchemaListener;
_busy: boolean;
_watching: boolean;
constructor(options: Options) {
super();
this.options = options;
if (!options) {
throw new Error("Please pass options to SchemaBuilder");
}
this._busy = false;
this._watching = false;
this.watchers = [];
this.unwatchers = [];
// Because hooks can nest, this keeps track of how deep we are.
this.depth = -1;
this.hooks = {
// The build object represents the current schema build and is passed to
// all hooks, hook the 'build' event to extend this object:
build: [],
// Inflection is used for naming resulting types/fields/args/etc - it's
// hookable so that other plugins may extend it or override it
inflection: [],
// 'build' phase should not generate any GraphQL objects (because the
// build object isn't finalised yet so it risks weirdness occurring); so
// if you need to set up any global types you can do so here.
init: [],
// 'finalize' phase is called once the schema is built; typically you
// shouldn't use this, but it's useful for interfacing with external
// libraries that mutate an already constructed schema.
finalize: [],
// Add 'query', 'mutation' or 'subscription' types in this hook:
GraphQLSchema: [],
// When creating a GraphQLObjectType via `newWithHooks`, we'll
// execute, the following hooks:
// - 'GraphQLObjectType' to add any root-level attributes, e.g. add a description
// - 'GraphQLObjectType:interfaces' to add additional interfaces to this object type
// - 'GraphQLObjectType:fields' to add additional fields to this object type (is
// ran asynchronously and gets a reference to the final GraphQL Object as
// `Self` in the context)
// - 'GraphQLObjectType:fields:field' to customise an individual field from above
// - 'GraphQLObjectType:fields:field:args' to customize the arguments to a field
GraphQLObjectType: [],
"GraphQLObjectType:interfaces": [],
"GraphQLObjectType:fields": [],
"GraphQLObjectType:fields:field": [],
"GraphQLObjectType:fields:field:args": [],
// When creating a GraphQLInputObjectType via `newWithHooks`, we'll
// execute, the following hooks:
// - 'GraphQLInputObjectType' to add any root-level attributes, e.g. add a description
// - 'GraphQLInputObjectType:fields' to add additional fields to this object type (is
// ran asynchronously and gets a reference to the final GraphQL Object as
// `Self` in the context)
// - 'GraphQLInputObjectType:fields:field' to customise an individual field from above
GraphQLInputObjectType: [],
"GraphQLInputObjectType:fields": [],
"GraphQLInputObjectType:fields:field": [],
// When creating a GraphQLEnumType via `newWithHooks`, we'll
// execute, the following hooks:
// - 'GraphQLEnumType' to add any root-level attributes, e.g. add a description
// - 'GraphQLEnumType:values' to add additional values
// - 'GraphQLEnumType:values:value' to change an individual value
GraphQLEnumType: [],
"GraphQLEnumType:values": [],
"GraphQLEnumType:values:value": [],
// When creating a GraphQLUnionType via `newWithHooks`, we'll
// execute, the following hooks:
// - 'GraphQLUnionType' to add any root-level attributes, e.g. add a description
// - 'GraphQLUnionType:types' to add additional types to this union
GraphQLUnionType: [],
"GraphQLUnionType:types": [],
};
}
_setPluginName(name: ?string) {
this._currentPluginName = name;
}
/*
* Every hook `fn` takes three arguments:
* - obj - the object currently being inspected
* - build - the current build object (which contains a number of utilities and the context of the build)
* - context - information specific to the current invocation of the hook
*
* The function must either return a replacement object for `obj` or `obj` itself
*/
hook<T: *>(
hookName: string,
fn: Hook<T, *, *>,
provides?: Array<string>,
before?: Array<string>,
after?: Array<string>
) {
if (!this.hooks[hookName]) {
throw new Error(`Sorry, '${hookName}' is not a supported hook`);
}
if (this._currentPluginName) {
fn.displayName = `${this._currentPluginName}/${hookName}/${(provides &&
provides.length &&
provides.join("+")) ||
fn.displayName ||
fn.name ||
"unnamed"}`;
}
if (provides) {
if (!fn.displayName && provides.length) {
fn.displayName = `unknown/${hookName}/${provides[0]}`;
}
fn.provides = provides;
}
if (before) {
fn.before = before;
}
if (after) {
fn.after = after;
}
if (!fn.provides && !fn.before && !fn.after) {
// No explicit dependencies - add to the end
this.hooks[hookName].push(fn);
} else {
// We need to figure out where it can go, respecting all the dependencies.
// TODO: I think there are situations in which this algorithm may result in unnecessary conflict errors; we should take a more iterative approach or find a better algorithm
const relevantHooks = this.hooks[hookName];
let minIndex = 0;
let minReason = null;
let maxIndex = relevantHooks.length;
let maxReason = null;
const { provides: newProvides, before: newBefore, after: newAfter } = fn;
const describe = (hook, index) => {
if (!hook) {
return "-";
}
return `${hook.displayName || hook.name || "anonymous"} (${
index ? `index: ${index}, ` : ""
}provides: ${hook.provides ? hook.provides.join(",") : "-"}, before: ${
hook.before ? hook.before.join(",") : "-"
}, after: ${hook.after ? hook.after.join(",") : "-"})`;
};
const check = () => {
if (minIndex > maxIndex) {
throw new Error(
`Cannot resolve plugin order - ${describe(
fn
)} cannot be before ${describe(
maxReason,
maxIndex
)} and after ${describe(
minReason,
minIndex
)} - please report this issue`
);
}
};
const setMin = (newMin, reason) => {
if (newMin > minIndex) {
minIndex = newMin;
minReason = reason;
check();
}
};
const setMax = (newMax, reason) => {
if (newMax < maxIndex) {
maxIndex = newMax;
maxReason = reason;
check();
}
};
relevantHooks.forEach((oldHook, idx) => {
const {
provides: oldProvides,
before: oldBefore,
after: oldAfter,
} = oldHook;
if (newProvides) {
if (oldBefore && oldBefore.some(dep => newProvides.includes(dep))) {
// Old says it has to come before new
setMin(idx + 1, oldHook);
}
if (oldAfter && oldAfter.some(dep => newProvides.includes(dep))) {
// Old says it has to be after new
setMax(idx, oldHook);
}
}
if (oldProvides) {
if (newBefore && newBefore.some(dep => oldProvides.includes(dep))) {
// New says it has to come before old
setMax(idx, oldHook);
}
if (newAfter && newAfter.some(dep => oldProvides.includes(dep))) {
// New says it has to be after old
setMin(idx + 1, oldHook);
}
}
});
// We've already validated everything, so we can now insert the record.
this.hooks[hookName].splice(maxIndex, 0, fn);
}
}
applyHooks<T: *, Context>(
build: { ...Build },
hookName: string,
input: T,
context: Context,
debugStr: string = ""
): T {
if (!input) {
throw new Error("applyHooks was called with falsy input");
}
this.depth++;
try {
debug(`${INDENT.repeat(this.depth)}[${hookName}${debugStr}]: Running...`);
const hooks: Array<Hook<T, *, *>> = this.hooks[hookName];
if (!hooks) {
throw new Error(`Sorry, '${hookName}' is not a registered hook`);
}
let newObj = input;
for (const hook: Hook<T, *, *> of hooks) {
this.depth++;
try {
const hookDisplayName = hook.displayName || hook.name || "anonymous";
debug(
`${INDENT.repeat(
this.depth
)}[${hookName}${debugStr}]: Executing '${hookDisplayName}'`
);
const previousHookName = build.status.currentHookName;
const previousHookEvent = build.status.currentHookEvent;
build.status.currentHookName = hookDisplayName;
build.status.currentHookEvent = hookName;
const oldObj = newObj;
newObj = hook(newObj, build, context);
if (hookName === "build") {
/*
* Unlike all the other hooks, the `build` hook must always use the
* same `build` object - never returning a new object for fear of
* causing issues to other build hooks that reference the old
* object and don't get the new additions.
*/
if (newObj !== oldObj) {
// TODO:v5: forbid this
// eslint-disable-next-line no-console
console.warn(
`Build hook '${hookDisplayName}' returned a new object; please use 'return build.extend(build, {...})' instead.`
);
// Copy everything from newObj back to oldObj
Object.assign(oldObj, newObj);
// Go back to the old objectect
newObj = oldObj;
}
}
build.status.currentHookName = previousHookName;
build.status.currentHookEvent = previousHookEvent;
if (!newObj) {
throw new Error(
`Hook '${hook.displayName ||
hook.name ||
"anonymous"}' for '${hookName}' returned falsy value '${newObj}'`
);
}
debug(
`${INDENT.repeat(
this.depth
)}[${hookName}${debugStr}]: '${hookDisplayName}' complete`
);
} finally {
this.depth--;
}
}
debug(`${INDENT.repeat(this.depth)}[${hookName}${debugStr}]: Complete`);
return newObj;
} finally {
this.depth--;
}
}
registerWatcher(listen: WatchUnwatch, unlisten: WatchUnwatch) {
if (!listen || !unlisten) {
throw new Error("You must provide both a listener and an unlistener");
}
this.watchers.push(listen);
this.unwatchers.push(unlisten);
}
createBuild(): { ...Build } {
const initialBuild = makeNewBuild(this);
// Inflection needs to come first, in case 'build' hooks depend on it
initialBuild.inflection = this.applyHooks(
initialBuild,
"inflection",
initialBuild.inflection,
{
scope: {},
}
);
const build = this.applyHooks(initialBuild, "build", initialBuild, {
scope: {},
});
// Bind all functions so they can be dereferenced
bindAll(
build,
Object.keys(build).filter(key => typeof build[key] === "function")
);
Object.freeze(build);
this.applyHooks(build, "init", {}, { scope: {} });
return build;
}
buildSchema(): GraphQLSchema {
if (!this._generatedSchema) {
const build = this.createBuild();
const schema = build.newWithHooks(
GraphQLSchema,
{
directives: [...build.graphql.specifiedDirectives],
},
{
__origin: `GraphQL built-in`,
isSchema: true,
}
);
this._generatedSchema = this.applyHooks(
build,
"finalize",
schema,
{},
"Finalising GraphQL schema"
);
}
if (!this._generatedSchema) {
throw new Error("Schema generation failed");
}
return this._generatedSchema;
}
async watchSchema(listener?: SchemaListener) {
if (this._busy) {
throw new Error("An operation is in progress");
}
if (this._watching) {
throw new Error(
"We're already watching this schema! Use `builder.on('schema', callback)` instead."
);
}
try {
this._busy = true;
this._explicitSchemaListener = listener;
this.triggerChange = () => {
this._generatedSchema = null;
// XXX: optionally debounce
try {
const schema = this.buildSchema();
this.emit("schema", schema);
} catch (e) {
// Build errors introduced while watching are ignored because it's
// primarily used in development.
// eslint-disable-next-line no-console
console.error(
"⚠️⚠️⚠️ An error occured when building the schema on watch:"
);
// eslint-disable-next-line no-console
console.error(e);
}
};
for (const fn of this.watchers) {
await fn(this.triggerChange);
}
if (listener) {
this.on("schema", listener);
}
this.emit("schema", this.buildSchema());
this._watching = true;
} finally {
this._busy = false;
}
}
async unwatchSchema() {
if (this._busy) {
throw new Error("An operation is in progress");
}
if (!this._watching) {
throw new Error("We're not watching this schema!");
}
this._busy = true;
try {
const listener = this._explicitSchemaListener;
this._explicitSchemaListener = null;
if (listener) {
this.removeListener("schema", listener);
}
if (this.triggerChange) {
for (const fn of this.unwatchers) {
await fn(this.triggerChange);
}
}
this.triggerChange = null;
this._watching = false;
} finally {
this._busy = false;
}
}
}
export default SchemaBuilder;