-
-
Notifications
You must be signed in to change notification settings - Fork 129
/
makeNewBuild.js
1126 lines (1078 loc) · 37.9 KB
/
makeNewBuild.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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @flow
import * as graphql from "graphql";
import type {
GraphQLNamedType,
GraphQLInputField,
GraphQLFieldResolver,
GraphQLType,
} from "graphql";
import {
parseResolveInfo,
simplifyParsedResolveInfoFragmentWithType,
getAliasFromResolveInfo as rawGetAliasFromResolveInfo,
} from "graphql-parse-resolve-info";
import debugFactory from "debug";
import type { ResolveTree } from "graphql-parse-resolve-info";
import pluralize from "pluralize";
import LRU from "@graphile/lru";
import semver from "semver";
import {
upperCamelCase,
camelCase,
constantCase,
wrapDescription,
} from "./utils";
import swallowError from "./swallowError";
import resolveNode from "./resolveNode";
import { LiveCoordinator } from "./Live";
import type SchemaBuilder, {
Build,
Context,
Scope,
DataForType,
} from "./SchemaBuilder";
import extend, { indent } from "./extend";
import chalk from "chalk";
import { createHash } from "crypto";
import { version } from "../package.json";
let recurseDataGeneratorsForFieldWarned = false;
const isString = str => typeof str === "string";
const isDev = ["test", "development"].indexOf(process.env.NODE_ENV) >= 0;
const debug = debugFactory("graphile-build");
/*
* This should be more than enough for normal usage. If you come under a
* sophisticated attack then the attacker can empty this of useful values (with
* a lot of work) but because we use SHA1 hashes under the covers the aliases
* will still be consistent even after the LRU cache is exhausted. And SHA1 can
* produce half a million hashes per second on my machine, the LRU only gives
* us a 10x speedup!
*/
const hashCache = new LRU({ maxLength: 100000 });
/*
* This function must never return a string longer than 56 characters.
*
* This function must only output alphanumeric and underscore characters.
*
* Collisions in SHA1 aren't problematic here (for us; they will be problematic
* for the user deliberately causing them, but that's their own fault!), so
* we'll happily take the performance boost over SHA256.
*/
function hashFieldAlias(str) {
const precomputed = hashCache.get(str);
if (precomputed) return precomputed;
const hash = createHash("sha1").update(str).digest("hex");
hashCache.set(str, hash);
return hash;
}
/*
* This function may be replaced at any time, but all versions of it will
* always return a representation of `alias` (a valid GraphQL identifier)
* that:
*
* 1. won't conflict with normal GraphQL field names
* 2. won't be over 60 characters long (allows for systems with alias length limits, such as PG)
* 3. will give the same value when called multiple times within the same GraphQL query
* 4. matches the regex /^[@!-_A-Za-z0-9]+$/
* 5. will not be prefixed with `__` (as that will conflict with other Graphile internals)
*
* It does not guarantee that this alias will be human readable!
*/
function getSafeAliasFromAlias(alias) {
if (alias.length <= 60 && !alias.startsWith("@")) {
// Use the `@` to prevent conflicting with normal GraphQL field names, but otherwise let it through verbatim.
return `@${alias}`;
} else if (alias.length > 1024) {
throw new Error(
`GraphQL alias '${alias}' is too long, use shorter aliases (max length 1024).`
);
} else {
return `@@${hashFieldAlias(alias)}`;
}
}
/*
* This provides a "safe" version of the alias from ResolveInfo, guaranteed to
* never be longer than 60 characters. This makes it suitable as a PostgreSQL
* identifier.
*/
function getSafeAliasFromResolveInfo(resolveInfo) {
const alias = rawGetAliasFromResolveInfo(resolveInfo);
return getSafeAliasFromAlias(alias);
}
type MetaData = {
[string]: Array<mixed>,
};
type DataGeneratorFunction = (
parsedResolveInfoFragment: ResolveTree,
ReturnType: GraphQLType,
...args: Array<mixed>
) => Array<MetaData>;
type FieldSpecIsh = {
type?: GraphQLType,
args?: {},
resolve?: GraphQLFieldResolver<*, *>,
deprecationReason?: string,
description?: ?string,
};
type ContextAndGenerators =
| Context
| {
addDataGenerator: DataGeneratorFunction => void,
addArgDataGenerator: DataGeneratorFunction => void,
getDataFromParsedResolveInfoFragment: (
parsedResolveInfoFragment: ResolveTree,
Type: GraphQLType
) => DataForType,
};
export type FieldWithHooksFunction = (
fieldName: string,
spec: FieldSpecIsh | (ContextAndGenerators => FieldSpecIsh),
fieldScope?: {}
) => {};
export type InputFieldWithHooksFunction = (
fieldName: string,
spec: GraphQLInputField,
fieldScope?: {}
) => GraphQLInputField;
function getNameFromType(Type: GraphQLNamedType | GraphQLSchema) {
if (Type instanceof GraphQLSchema) {
return "schema";
} else {
return Type.name;
}
}
const {
GraphQLSchema,
GraphQLInterfaceType,
GraphQLObjectType,
GraphQLInputObjectType,
GraphQLEnumType,
GraphQLUnionType,
getNamedType,
isCompositeType,
isAbstractType,
} = graphql;
const mergeData = (
data: MetaData,
gen: DataGeneratorFunction,
ReturnType,
arg
) => {
const results: ?Array<MetaData> = ensureArray<MetaData>(
gen(arg, ReturnType, data)
);
if (!results) {
return;
}
for (
let resultIndex = 0, resultCount = results.length;
resultIndex < resultCount;
resultIndex++
) {
const result: MetaData = results[resultIndex];
const keys = Object.keys(result);
for (let i = 0, l = keys.length; i < l; i++) {
const k = keys[i];
data[k] = data[k] || [];
const value: mixed = result[k];
const newData: ?Array<mixed> = ensureArray<mixed>(value);
if (newData) {
data[k].push(...newData);
}
}
}
};
const knownTypes = [
GraphQLSchema,
GraphQLObjectType,
GraphQLInputObjectType,
GraphQLEnumType,
GraphQLUnionType,
];
const knownTypeNames = knownTypes.map(k => k.name);
function ensureArray<T>(val: null | T | Array<T>): void | Array<T> {
if (val == null) {
return;
} else if (Array.isArray(val)) {
// $FlowFixMe
return (val: Array<T>);
} else {
return ([val]: Array<T>);
}
}
// eslint-disable-next-line no-unused-vars
let ensureName = _fn => {};
if (["development", "test"].indexOf(process.env.NODE_ENV) >= 0) {
ensureName = fn => {
// $FlowFixMe: displayName
if (isDev && !fn.displayName && !fn.name && debug.enabled) {
// eslint-disable-next-line no-console
console.trace(
"WARNING: you've added a function with no name as an argDataGenerator, doing so may make debugging more challenging"
);
}
};
}
export default function makeNewBuild(builder: SchemaBuilder): { ...Build } {
const allTypes = {
Int: graphql.GraphQLInt,
Float: graphql.GraphQLFloat,
String: graphql.GraphQLString,
Boolean: graphql.GraphQLBoolean,
ID: graphql.GraphQLID,
};
const allTypesSources = {
Int: "GraphQL Built-in",
Float: "GraphQL Built-in",
String: "GraphQL Built-in",
Boolean: "GraphQL Built-in",
ID: "GraphQL Built-in",
};
// Every object type gets fieldData associated with each of its
// fields.
// When a field is defined, it may add to this field data.
// When something resolves referencing this type, the resolver may
// request the fieldData, e.g. to perform optimisations.
// fieldData is an object whose keys are the fields on this
// GraphQLObjectType and whose values are an object (whose keys are
// arbitrary namespaced keys and whose values are arrays of
// information of this kind)
const fieldDataGeneratorsByFieldNameByType = new Map();
const fieldArgDataGeneratorsByFieldNameByType = new Map();
return {
options: builder.options,
graphileBuildVersion: version,
versions: {
graphql: require("graphql/package.json").version,
"graphile-build": version,
},
hasVersion(
packageName: string,
range: string,
options?: { includePrerelease?: boolean } = { includePrerelease: true }
): boolean {
const packageVersion = this.versions[packageName];
if (!packageVersion) return false;
return semver.satisfies(packageVersion, range, options);
},
graphql,
parseResolveInfo,
simplifyParsedResolveInfoFragmentWithType,
getSafeAliasFromAlias,
getAliasFromResolveInfo: getSafeAliasFromResolveInfo, // DEPRECATED: do not use this!
getSafeAliasFromResolveInfo,
resolveAlias(data, _args, _context, resolveInfo) {
const alias = getSafeAliasFromResolveInfo(resolveInfo);
return data[alias];
},
addType(type: GraphQLNamedType, origin?: ?string): void {
if (!type.name) {
throw new Error(
`addType must only be called with named types, try using require('graphql').getNamedType`
);
}
const newTypeSource =
origin ||
// 'this' is typically only available after the build is finalized
(this
? `'addType' call during hook '${this.status.currentHookName}'`
: null);
if (allTypes[type.name]) {
if (allTypes[type.name] !== type) {
const oldTypeSource = allTypesSources[type.name];
const firstEntityDetails = !oldTypeSource
? "The first type was registered from an unknown origin."
: `The first entity was:\n\n${indent(
chalk.magenta(oldTypeSource)
)}`;
const secondEntityDetails = !newTypeSource
? "The second type was registered from an unknown origin."
: `The second entity was:\n\n${indent(
chalk.yellow(newTypeSource)
)}`;
throw new Error(
`A type naming conflict has occurred - two entities have tried to define the same type '${chalk.bold(
type.name
)}'.\n\n${indent(firstEntityDetails)}\n\n${indent(
secondEntityDetails
)}`
);
}
} else {
allTypes[type.name] = type;
allTypesSources[type.name] = newTypeSource;
}
},
getTypeByName(typeName) {
return allTypes[typeName];
},
extend,
newWithHooks<T: GraphQLNamedType | GraphQLSchema, ConfigType: *>(
Type: Class<T>,
spec: ConfigType,
inScope: Scope,
performNonEmptyFieldsCheck = false
): ?T {
const scope = inScope || {};
if (!inScope) {
// eslint-disable-next-line no-console
console.warn(
`No scope was provided to new ${Type.name}[name=${spec.name}], it's highly recommended that you add a scope so other hooks can easily reference your object - please check usage of 'newWithHooks'. To mute this message, just pass an empty object.`
);
}
if (!Type) {
throw new Error("No type specified!");
}
if (!this.newWithHooks) {
throw new Error(
"Please do not generate the schema during the build building phase, use 'init' instead"
);
}
const fieldDataGeneratorsByFieldName = {};
const fieldArgDataGeneratorsByFieldName = {};
let newSpec = spec;
if (
knownTypes.indexOf(Type) === -1 &&
knownTypeNames.indexOf(Type.name) >= 0
) {
throw new Error(
`GraphQL conflict for '${Type.name}' detected! Multiple versions of graphql exist in your node_modules?`
);
}
if (Type === GraphQLSchema) {
newSpec = builder.applyHooks(this, "GraphQLSchema", newSpec, {
type: "GraphQLSchema",
scope,
});
} else if (Type === GraphQLObjectType) {
const addDataGeneratorForField = (
fieldName,
fn: DataGeneratorFunction
) => {
// $FlowFixMe: displayName
fn.displayName =
// $FlowFixMe: displayName
fn.displayName ||
`${getNameFromType(Self)}:${fieldName}[${fn.name || "anonymous"}]`;
fieldDataGeneratorsByFieldName[fieldName] =
fieldDataGeneratorsByFieldName[fieldName] || [];
fieldDataGeneratorsByFieldName[fieldName].push(fn);
};
const recurseDataGeneratorsForField = (
fieldName,
iKnowWhatIAmDoing
) => {
/*
* Recursing data generators is not safe in general; however there
* are certain exceptions - for example when you know there are no
* "dynamic" data generator fields - e.g. where the GraphQL alias is
* not used at all. In PostGraphile the only case of this is the
* PageInfo object as none of the fields accept arguments, and they
* do not rely on the GraphQL query alias to store the result.
*/
if (!iKnowWhatIAmDoing && !recurseDataGeneratorsForFieldWarned) {
recurseDataGeneratorsForFieldWarned = true;
// eslint-disable-next-line no-console
console.error(
"Use of `recurseDataGeneratorsForField` is NOT SAFE. e.g. `{n1: node { a: field1 }, n2: node { a: field2 } }` cannot resolve correctly."
);
}
const fn = (parsedResolveInfoFragment, ReturnType, ...rest) => {
const { args } = parsedResolveInfoFragment;
const { fields } = this.simplifyParsedResolveInfoFragmentWithType(
parsedResolveInfoFragment,
ReturnType
);
const results = [];
const StrippedType: GraphQLNamedType = getNamedType(ReturnType);
const fieldDataGeneratorsByFieldName = fieldDataGeneratorsByFieldNameByType.get(
StrippedType
);
const argDataGeneratorsForSelfByFieldName = fieldArgDataGeneratorsByFieldNameByType.get(
Self
);
if (argDataGeneratorsForSelfByFieldName) {
const argDataGenerators =
argDataGeneratorsForSelfByFieldName[fieldName];
for (
let genIndex = 0, genCount = argDataGenerators.length;
genIndex < genCount;
genIndex++
) {
const gen = argDataGenerators[genIndex];
const local = ensureArray(gen(args, ReturnType, ...rest));
if (local) {
results.push(...local);
}
}
}
if (
fieldDataGeneratorsByFieldName &&
isCompositeType(StrippedType) &&
!isAbstractType(StrippedType)
) {
const typeFields = StrippedType.getFields();
const keys = Object.keys(fields);
for (
let keyIndex = 0, keyCount = keys.length;
keyIndex < keyCount;
keyIndex++
) {
const alias = keys[keyIndex];
const field = fields[alias];
// Run generators with `field` as the `parsedResolveInfoFragment`, pushing results to `results`
const gens = fieldDataGeneratorsByFieldName[field.name];
if (gens) {
for (
let genIndex = 0, genCount = gens.length;
genIndex < genCount;
genIndex++
) {
const gen = gens[genIndex];
const local = ensureArray(
gen(field, typeFields[field.name].type, ...rest)
);
if (local) {
results.push(...local);
}
}
}
}
}
return results;
};
fn.displayName = `recurseDataGeneratorsForField(${getNameFromType(
Self
)}:${fieldName})`;
addDataGeneratorForField(fieldName, fn);
// get type from field, get
};
const commonContext = {
type: "GraphQLObjectType",
scope,
};
newSpec = builder.applyHooks(
this,
"GraphQLObjectType",
newSpec,
{
...commonContext,
addDataGeneratorForField,
recurseDataGeneratorsForField,
},
`|${newSpec.name}`
);
const rawSpec = newSpec;
newSpec = {
...newSpec,
interfaces: () => {
const interfacesContext = {
...commonContext,
Self,
GraphQLObjectType: rawSpec,
};
let rawInterfaces = rawSpec.interfaces || [];
if (typeof rawInterfaces === "function") {
rawInterfaces = rawInterfaces(interfacesContext);
}
return builder.applyHooks(
this,
"GraphQLObjectType:interfaces",
rawInterfaces,
interfacesContext,
`|${getNameFromType(Self)}`
);
},
fields: () => {
const processedFields = [];
const fieldsContext = {
...commonContext,
addDataGeneratorForField,
recurseDataGeneratorsForField,
Self,
GraphQLObjectType: rawSpec,
fieldWithHooks: ((fieldName, spec, fieldScope) => {
if (!isString(fieldName)) {
throw new Error(
"It looks like you forgot to pass the fieldName to `fieldWithHooks`, we're sorry this is currently necessary."
);
}
if (!fieldScope) {
throw new Error(
"All calls to `fieldWithHooks` must specify a `fieldScope` " +
"argument that gives additional context about the field so " +
"that further plugins may more easily understand the field. " +
"Keys within this object should contain the phrase 'field' " +
"since they will be merged into the parent objects scope and " +
"are not allowed to clash. If you really have no additional " +
"information to give, please just pass `{}`."
);
}
const argDataGenerators = [];
fieldArgDataGeneratorsByFieldName[
fieldName
] = argDataGenerators;
let newSpec = spec;
const context = {
...commonContext,
Self,
addDataGenerator(fn) {
return addDataGeneratorForField(fieldName, fn);
},
addArgDataGenerator(fn) {
ensureName(fn);
argDataGenerators.push(fn);
},
getDataFromParsedResolveInfoFragment: (
parsedResolveInfoFragment,
ReturnType
): DataForType => {
const Type: GraphQLNamedType = getNamedType(ReturnType);
const data = {};
const {
fields,
args,
} = this.simplifyParsedResolveInfoFragmentWithType(
parsedResolveInfoFragment,
ReturnType
);
// Args -> argDataGenerators
for (
let dgIndex = 0, dgCount = argDataGenerators.length;
dgIndex < dgCount;
dgIndex++
) {
const gen = argDataGenerators[dgIndex];
try {
mergeData(data, gen, ReturnType, args);
} catch (e) {
debug(
"Failed to execute argDataGenerator '%s' on %s of %s",
gen.displayName || gen.name || "anonymous",
fieldName,
getNameFromType(Self)
);
throw e;
}
}
// finalSpec.type -> fieldData
if (!finalSpec) {
throw new Error(
"It's too early to call this! Call from within resolve"
);
}
const fieldDataGeneratorsByFieldName = fieldDataGeneratorsByFieldNameByType.get(
Type
);
if (
fieldDataGeneratorsByFieldName &&
isCompositeType(Type) &&
!isAbstractType(Type)
) {
const typeFields = Type.getFields();
const keys = Object.keys(fields);
for (
let keyIndex = 0, keyCount = keys.length;
keyIndex < keyCount;
keyIndex++
) {
const alias = keys[keyIndex];
const field = fields[alias];
const gens = fieldDataGeneratorsByFieldName[field.name];
if (gens) {
const FieldReturnType = typeFields[field.name].type;
for (let i = 0, l = gens.length; i < l; i++) {
mergeData(data, gens[i], FieldReturnType, field);
}
}
}
}
return data;
},
scope: extend(
extend(
{ ...scope },
{
fieldName,
},
`Within context for GraphQLObjectType '${rawSpec.name}'`
),
fieldScope,
`Extending scope for field '${fieldName}' within context for GraphQLObjectType '${rawSpec.name}'`
),
};
if (typeof newSpec === "function") {
newSpec = newSpec(context);
}
newSpec = builder.applyHooks(
this,
"GraphQLObjectType:fields:field",
newSpec,
context,
`|${getNameFromType(Self)}.fields.${fieldName}`
);
newSpec.args = newSpec.args || {};
newSpec = {
...newSpec,
args: builder.applyHooks(
this,
"GraphQLObjectType:fields:field:args",
newSpec.args,
{
...context,
field: newSpec,
returnType: newSpec.type,
},
`|${getNameFromType(Self)}.fields.${fieldName}`
),
};
const finalSpec = newSpec;
processedFields.push(finalSpec);
return finalSpec;
}: FieldWithHooksFunction),
};
let rawFields = rawSpec.fields || {};
if (typeof rawFields === "function") {
rawFields = rawFields(fieldsContext);
}
const fieldsSpec = builder.applyHooks(
this,
"GraphQLObjectType:fields",
this.extend(
{},
rawFields,
`Default field included in newWithHooks call for '${
rawSpec.name
}'. ${inScope.__origin || ""}`
),
fieldsContext,
`|${rawSpec.name}`
);
// Finally, check through all the fields that they've all been processed; any that have not we should do so now.
for (const fieldName in fieldsSpec) {
const fieldSpec = fieldsSpec[fieldName];
if (processedFields.indexOf(fieldSpec) < 0) {
// We've not processed this yet; process it now!
fieldsSpec[fieldName] = fieldsContext.fieldWithHooks(
fieldName,
fieldSpec,
{
autoField: true, // We don't have any additional information
}
);
}
}
return fieldsSpec;
},
};
} else if (Type === GraphQLInputObjectType) {
const commonContext = {
type: "GraphQLInputObjectType",
scope,
};
newSpec = builder.applyHooks(
this,
"GraphQLInputObjectType",
newSpec,
commonContext,
`|${newSpec.name}`
);
newSpec.fields = newSpec.fields || {};
const rawSpec = newSpec;
newSpec = {
...newSpec,
fields: () => {
const processedFields = [];
const fieldsContext = {
...commonContext,
Self,
GraphQLInputObjectType: rawSpec,
fieldWithHooks: ((fieldName, spec, fieldScope = {}) => {
if (!isString(fieldName)) {
throw new Error(
"It looks like you forgot to pass the fieldName to `fieldWithHooks`, we're sorry this is currently necessary."
);
}
const context = {
...commonContext,
Self,
scope: extend(
extend(
{ ...scope },
{
fieldName,
},
`Within context for GraphQLInputObjectType '${rawSpec.name}'`
),
fieldScope,
`Extending scope for field '${fieldName}' within context for GraphQLInputObjectType '${rawSpec.name}'`
),
};
let newSpec = spec;
if (typeof newSpec === "function") {
newSpec = newSpec(context);
}
newSpec = builder.applyHooks(
this,
"GraphQLInputObjectType:fields:field",
newSpec,
context,
`|${getNameFromType(Self)}.fields.${fieldName}`
);
const finalSpec = newSpec;
processedFields.push(finalSpec);
return finalSpec;
}: InputFieldWithHooksFunction),
};
let rawFields = rawSpec.fields;
if (typeof rawFields === "function") {
rawFields = rawFields(fieldsContext);
}
const fieldsSpec = builder.applyHooks(
this,
"GraphQLInputObjectType:fields",
this.extend(
{},
rawFields,
`Default field included in newWithHooks call for '${
rawSpec.name
}'. ${inScope.__origin || ""}`
),
fieldsContext,
`|${getNameFromType(Self)}`
);
// Finally, check through all the fields that they've all been processed; any that have not we should do so now.
for (const fieldName in fieldsSpec) {
const fieldSpec = fieldsSpec[fieldName];
if (processedFields.indexOf(fieldSpec) < 0) {
// We've not processed this yet; process it now!
fieldsSpec[fieldName] = fieldsContext.fieldWithHooks(
fieldName,
fieldSpec,
{
autoField: true, // We don't have any additional information
}
);
}
}
return fieldsSpec;
},
};
} else if (Type === GraphQLEnumType) {
const commonContext = {
type: "GraphQLEnumType",
scope,
};
newSpec = builder.applyHooks(
this,
"GraphQLEnumType",
newSpec,
commonContext,
`|${newSpec.name}`
);
newSpec.values = builder.applyHooks(
this,
"GraphQLEnumType:values",
newSpec.values,
commonContext,
`|${newSpec.name}`
);
const values = newSpec.values;
newSpec.values = Object.keys(values).reduce((memo, valueKey) => {
const value = values[valueKey];
const newValue = builder.applyHooks(
this,
"GraphQLEnumType:values:value",
value,
commonContext,
`|${newSpec.name}|${valueKey}`
);
memo[valueKey] = newValue;
return memo;
}, {});
} else if (Type === GraphQLUnionType) {
const commonContext = {
type: "GraphQLUnionType",
scope,
};
newSpec = builder.applyHooks(
this,
"GraphQLUnionType",
newSpec,
{ ...commonContext },
`|${newSpec.name}`
);
const rawSpec = newSpec;
newSpec = {
...newSpec,
types: () => {
const typesContext = {
...commonContext,
Self,
GraphQLUnionType: rawSpec,
};
let rawTypes = rawSpec.types || [];
if (typeof rawTypes === "function") {
rawTypes = rawTypes(typesContext);
}
return builder.applyHooks(
this,
"GraphQLUnionType:types",
rawTypes,
typesContext,
`|${getNameFromType(Self)}`
);
},
};
} else if (Type === GraphQLInterfaceType) {
const commonContext = {
type: "GraphQLInterfaceType",
scope,
};
newSpec = builder.applyHooks(
this,
"GraphQLInterfaceType",
newSpec,
commonContext,
`|${newSpec.name}`
);
const rawSpec = newSpec;
newSpec = {
...newSpec,
fields: () => {
const processedFields = [];
const fieldsContext = {
...commonContext,
Self,
GraphQLInterfaceType: rawSpec,
fieldWithHooks: ((fieldName, spec, fieldScope) => {
if (!isString(fieldName)) {
throw new Error(
"It looks like you forgot to pass the fieldName to `fieldWithHooks`, we're sorry this is currently necessary."
);
}
if (!fieldScope) {
throw new Error(
"All calls to `fieldWithHooks` must specify a `fieldScope` " +
"argument that gives additional context about the field so " +
"that further plugins may more easily understand the field. " +
"Keys within this object should contain the phrase 'field' " +
"since they will be merged into the parent objects scope and " +
"are not allowed to clash. If you really have no additional " +
"information to give, please just pass `{}`."
);
}
let newSpec = spec;
const context = {
...commonContext,
Self,
scope: extend(
extend(
{ ...scope },
{
fieldName,
},
`Within context for GraphQLInterfaceType '${rawSpec.name}'`
),
fieldScope,
`Extending scope for field '${fieldName}' within context for GraphQLInterfaceType '${rawSpec.name}'`
),
};
if (typeof newSpec === "function") {
newSpec = newSpec(context);
}
newSpec = builder.applyHooks(
this,
"GraphQLInterfaceType:fields:field",
newSpec,
context,
`|${getNameFromType(Self)}.fields.${fieldName}`
);
newSpec.args = newSpec.args || {};
newSpec = {
...newSpec,
args: builder.applyHooks(
this,
"GraphQLInterfaceType:fields:field:args",
newSpec.args,
{
...context,
field: newSpec,
returnType: newSpec.type,
},
`|${getNameFromType(Self)}.fields.${fieldName}`
),
};
const finalSpec = newSpec;
processedFields.push(finalSpec);
return finalSpec;
}: FieldWithHooksFunction),
};
let rawFields = rawSpec.fields || {};
if (typeof rawFields === "function") {
rawFields = rawFields(fieldsContext);
}
const fieldsSpec = builder.applyHooks(
this,
"GraphQLInterfaceType:fields",
this.extend(
{},
rawFields,
`Default field included in newWithHooks call for '${
rawSpec.name
}'. ${inScope.__origin || ""}`
),
fieldsContext,
`|${rawSpec.name}`
);
// Finally, check through all the fields that they've all been processed; any that have not we should do so now.
for (const fieldName in fieldsSpec) {
const fieldSpec = fieldsSpec[fieldName];
if (processedFields.indexOf(fieldSpec) < 0) {
// We've not processed this yet; process it now!
fieldsSpec[fieldName] = fieldsContext.fieldWithHooks(
fieldName,
fieldSpec,
{
autoField: true, // We don't have any additional information
}
);
}
}
return fieldsSpec;
},
};
}
const finalSpec: ConfigType = newSpec;
const Self: T = new Type(finalSpec);
if (!(Self instanceof GraphQLSchema) && performNonEmptyFieldsCheck) {
try {
if (
Self instanceof GraphQLInterfaceType ||
Self instanceof GraphQLObjectType ||
Self instanceof GraphQLInputObjectType
) {
const _Self:
| GraphQLInterfaceType
| GraphQLInputObjectType
| GraphQLObjectType = Self;
if (typeof _Self.getFields === "function") {
const fields = _Self.getFields();