/
schema.js
1435 lines (1343 loc) · 44 KB
/
schema.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
const _ = require(`lodash`)
const invariant = require(`invariant`)
const {
isSpecifiedScalarType,
isIntrospectionType,
assertValidName,
GraphQLNonNull,
GraphQLList,
GraphQLObjectType,
GraphQLInterfaceType,
GraphQLUnionType,
} = require(`graphql`)
const {
ObjectTypeComposer,
InterfaceTypeComposer,
UnionTypeComposer,
InputTypeComposer,
ScalarTypeComposer,
EnumTypeComposer,
} = require(`graphql-compose`)
const { getDataStore, getNode, getNodesByType } = require(`../datastore`)
const apiRunner = require(`../utils/api-runner-node`)
const report = require(`gatsby-cli/lib/reporter`)
const { addNodeInterfaceFields } = require(`./types/node-interface`)
const {
overridableBuiltInTypeNames,
builtInScalarTypeNames,
} = require(`./types/built-in-types`)
const { addInferredTypes } = require(`./infer`)
const {
addRemoteFileInterfaceFields,
} = require(`./types/remote-file-interface`)
const {
findOne,
findManyPaginated,
wrappingResolver,
defaultResolver,
} = require(`./resolvers`)
const {
processFieldExtensions,
internalExtensionNames,
} = require(`./extensions`)
import { getPagination } from "./types/pagination"
import { getSortInput, SORTABLE_ENUM } from "./types/sort"
import { getFilterInput, SEARCHABLE_ENUM } from "./types/filter"
import { isGatsbyType, GatsbyGraphQLTypeKind } from "./types/type-builders"
const {
isASTDocument,
parseTypeDef,
reportParsingError,
} = require(`./types/type-defs`)
const { printTypeDefinitions } = require(`./print`)
const buildSchema = async ({
schemaComposer,
types,
typeMapping,
fieldExtensions,
thirdPartySchemas,
printConfig,
enginePrintConfig,
typeConflictReporter,
inferenceMetadata,
parentSpan,
}) => {
// FIXME: consider removing .ready here - it is needed for various tests to pass (although probably harmless)
await getDataStore().ready()
await updateSchemaComposer({
schemaComposer,
types,
typeMapping,
fieldExtensions,
thirdPartySchemas,
printConfig,
enginePrintConfig,
typeConflictReporter,
inferenceMetadata,
parentSpan,
})
// const { printSchema } = require(`graphql`)
const schema = schemaComposer.buildSchema()
freezeTypeComposers(schemaComposer)
// console.log(printSchema(schema))
return schema
}
module.exports = {
buildSchema,
}
// Workaround for https://github.com/graphql-compose/graphql-compose/issues/319
// FIXME: remove this when fixed in graphql-compose
const freezeTypeComposers = (schemaComposer, excluded = new Set()) => {
Array.from(schemaComposer.values()).forEach(tc => {
const isCompositeTC =
tc instanceof ObjectTypeComposer || tc instanceof InterfaceTypeComposer
if (isCompositeTC && !excluded.has(tc.getTypeName())) {
// typeComposer.getType() actually mutates the underlying GraphQL type
// and always re-assigns type._fields with a thunk.
// It causes continuous redundant field re-definitions when running queries
// (affects performance significantly).
// Prevent the mutation and "freeze" the type:
const type = tc.getType()
tc.getType = () => type
}
})
}
const updateSchemaComposer = async ({
schemaComposer,
types,
typeMapping,
fieldExtensions,
thirdPartySchemas,
printConfig,
enginePrintConfig,
typeConflictReporter,
inferenceMetadata,
parentSpan,
}) => {
let activity = report.phantomActivity(`Add explicit types`, {
parentSpan: parentSpan,
})
activity.start()
await addTypes({ schemaComposer, parentSpan: activity.span, types })
activity.end()
activity = report.phantomActivity(`Add inferred types`, {
parentSpan: parentSpan,
})
activity.start()
await addInferredTypes({
schemaComposer,
typeConflictReporter,
typeMapping,
inferenceMetadata,
parentSpan: activity.span,
})
addInferredChildOfExtensions({
schemaComposer,
})
activity.end()
activity = report.phantomActivity(`Processing types`, {
parentSpan: parentSpan,
})
activity.start()
if (!process.env.GATSBY_SKIP_WRITING_SCHEMA_TO_FILE) {
await printTypeDefinitions({
config: printConfig,
schemaComposer,
parentSpan: activity.span,
})
if (enginePrintConfig) {
// make sure to print schema that will be used when bundling graphql-engine
await printTypeDefinitions({
config: enginePrintConfig,
schemaComposer,
parentSpan: activity.span,
})
}
}
await addSetFieldsOnGraphQLNodeTypeFields({
schemaComposer,
parentSpan: activity.span,
})
await addConvenienceChildrenFields({
schemaComposer,
parentSpan: activity.span,
})
await Promise.all(
Array.from(new Set(schemaComposer.values())).map(typeComposer =>
processTypeComposer({
schemaComposer,
typeComposer,
fieldExtensions,
parentSpan: activity.span,
})
)
)
checkQueryableInterfaces({ schemaComposer, parentSpan: activity.span })
await addThirdPartySchemas({
schemaComposer,
thirdPartySchemas,
parentSpan: activity.span,
})
await addCustomResolveFunctions({ schemaComposer, parentSpan: activity.span })
attachTracingResolver({ schemaComposer, parentSpan: activity.span })
activity.end()
}
const processTypeComposer = async ({
schemaComposer,
typeComposer,
fieldExtensions,
parentSpan,
}) => {
if (typeComposer instanceof ObjectTypeComposer) {
await processFieldExtensions({
schemaComposer,
typeComposer,
fieldExtensions,
parentSpan,
})
if (typeComposer.hasInterface(`Node`)) {
await addNodeInterfaceFields({ schemaComposer, typeComposer })
}
if (typeComposer.hasInterface(`RemoteFile`)) {
addRemoteFileInterfaceFields(schemaComposer, typeComposer)
}
await determineSearchableFields({
schemaComposer,
typeComposer,
parentSpan,
})
if (typeComposer.hasInterface(`Node`)) {
await addTypeToRootQuery({ schemaComposer, typeComposer, parentSpan })
}
} else if (typeComposer instanceof InterfaceTypeComposer) {
if (isNodeInterface(typeComposer)) {
await addNodeInterfaceFields({ schemaComposer, typeComposer, parentSpan })
// We only process field extensions for queryable Node interfaces, so we get
// the input args on the root query type, e.g. `formatString` etc. for `dateformat`
await processFieldExtensions({
schemaComposer,
typeComposer,
fieldExtensions,
parentSpan,
})
await determineSearchableFields({
schemaComposer,
typeComposer,
parentSpan,
})
await addTypeToRootQuery({ schemaComposer, typeComposer, parentSpan })
}
}
}
const fieldNames = {
query: typeName => _.camelCase(typeName),
queryAll: typeName => _.camelCase(`all ${typeName}`),
convenienceChild: typeName => _.camelCase(`child ${typeName}`),
convenienceChildren: typeName => _.camelCase(`children ${typeName}`),
}
const addTypes = ({ schemaComposer, types, parentSpan }) => {
types.forEach(({ typeOrTypeDef, plugin }) => {
if (typeof typeOrTypeDef === `string`) {
typeOrTypeDef = parseTypeDef(typeOrTypeDef)
}
if (isASTDocument(typeOrTypeDef)) {
let parsedTypes
const createdFrom = `sdl`
try {
parsedTypes = parseTypes({
doc: typeOrTypeDef,
plugin,
createdFrom,
schemaComposer,
parentSpan,
})
} catch (error) {
reportParsingError(error)
return
}
parsedTypes.forEach(type => {
processAddedType({
schemaComposer,
type,
parentSpan,
createdFrom,
plugin,
})
})
} else if (isGatsbyType(typeOrTypeDef)) {
const type = createTypeComposerFromGatsbyType({
schemaComposer,
type: typeOrTypeDef,
parentSpan,
})
if (type) {
const typeName = type.getTypeName()
const createdFrom = `typeBuilder`
checkIsAllowedTypeName(typeName)
if (schemaComposer.has(typeName)) {
const typeComposer = schemaComposer.get(typeName)
mergeTypes({
schemaComposer,
typeComposer,
type,
plugin,
createdFrom,
parentSpan,
})
} else {
processAddedType({
schemaComposer,
type,
parentSpan,
createdFrom,
plugin,
})
}
}
} else {
const typeName = typeOrTypeDef.name
const createdFrom = `graphql-js`
checkIsAllowedTypeName(typeName)
if (schemaComposer.has(typeName)) {
const typeComposer = schemaComposer.get(typeName)
mergeTypes({
schemaComposer,
typeComposer,
type: typeOrTypeDef,
plugin,
createdFrom,
parentSpan,
})
} else {
processAddedType({
schemaComposer,
type: typeOrTypeDef,
parentSpan,
createdFrom,
plugin,
})
}
}
})
}
const mergeTypes = ({
schemaComposer,
typeComposer,
type,
plugin,
createdFrom,
parentSpan,
}) => {
// The merge is considered safe when a user or a plugin owning the type extend this type
// TODO: add proper conflicts detection and reporting (on the field level)
const typeOwner = typeComposer.getExtension(`plugin`)
const isOverridableBuiltInType =
!typeOwner && overridableBuiltInTypeNames.has(typeComposer.getTypeName())
const isSafeMerge =
!plugin ||
plugin.name === `default-site-plugin` ||
plugin.name === typeOwner ||
typeComposer.hasExtension(`isPlaceholder`) ||
isOverridableBuiltInType
if (!isSafeMerge) {
if (typeOwner) {
report.warn(
`Plugin \`${plugin.name}\` has customized the GraphQL type ` +
`\`${typeComposer.getTypeName()}\`, which has already been defined ` +
`by the plugin \`${typeOwner}\`. ` +
`This could potentially cause conflicts.`
)
} else {
report.warn(
`Plugin \`${plugin.name}\` has customized the built-in Gatsby GraphQL type ` +
`\`${typeComposer.getTypeName()}\`. ` +
`This is allowed, but could potentially cause conflicts.`
)
}
}
if (
type instanceof ObjectTypeComposer ||
type instanceof InterfaceTypeComposer ||
type instanceof GraphQLObjectType ||
type instanceof GraphQLInterfaceType
) {
mergeFields({ typeComposer, fields: type.getFields() })
type.getInterfaces().forEach(iface => typeComposer.addInterface(iface))
}
if (
type instanceof GraphQLInterfaceType ||
type instanceof InterfaceTypeComposer ||
type instanceof GraphQLUnionType ||
type instanceof UnionTypeComposer
) {
mergeResolveType({ typeComposer, type })
}
let extensions = {}
if (isNamedTypeComposer(type)) {
if (createdFrom === `sdl`) {
extensions = convertDirectivesToExtensions(type, type.getDirectives())
} else {
typeComposer.extendExtensions(type.getExtensions())
}
}
addExtensions({
schemaComposer,
typeComposer,
extensions,
plugin,
createdFrom,
})
return true
}
const processAddedType = ({
schemaComposer,
type,
parentSpan,
createdFrom,
plugin,
}) => {
const typeName = schemaComposer.add(type)
const typeComposer = schemaComposer.get(typeName)
if (
typeComposer instanceof InterfaceTypeComposer ||
typeComposer instanceof UnionTypeComposer
) {
if (!typeComposer.getResolveType()) {
typeComposer.setResolveType(node => node.internal.type)
}
}
schemaComposer.addSchemaMustHaveType(typeComposer)
let extensions = {}
if (createdFrom === `sdl`) {
extensions = convertDirectivesToExtensions(
typeComposer,
typeComposer.getDirectives()
)
}
addExtensions({
schemaComposer,
typeComposer,
extensions,
plugin,
createdFrom,
})
return typeComposer
}
/**
* @param {import("graphql-compose").AnyTypeComposer} typeComposer
* @param {Array<import("graphql-compose").Directive>} directives
* @return {{infer?: boolean, mimeTypes?: { types: Array<string> }, childOf?: { types: Array<string> }, nodeInterface?: boolean}}
*/
const convertDirectivesToExtensions = (typeComposer, directives) => {
const extensions = {}
directives.forEach(({ name, args }) => {
switch (name) {
case `infer`:
case `dontInfer`: {
extensions[`infer`] = name === `infer`
break
}
case `mimeTypes`:
extensions[`mimeTypes`] = args
break
case `childOf`:
extensions[`childOf`] = args
break
case `nodeInterface`:
if (typeComposer instanceof InterfaceTypeComposer) {
extensions[`nodeInterface`] = true
}
break
default:
}
})
return extensions
}
const addExtensions = ({
schemaComposer,
typeComposer,
extensions = {},
plugin,
createdFrom,
}) => {
typeComposer.setExtension(`createdFrom`, createdFrom)
typeComposer.setExtension(`plugin`, plugin ? plugin.name : null)
typeComposer.extendExtensions(extensions)
if (
typeComposer instanceof InterfaceTypeComposer &&
isNodeInterface(typeComposer)
) {
const hasCorrectIdField =
typeComposer.hasField(`id`) &&
typeComposer.getFieldType(`id`).toString() === `ID!`
if (!hasCorrectIdField) {
report.panic(
`Interfaces with the \`nodeInterface\` extension must have a field ` +
`\`id\` of type \`ID!\`. Check the type definition of ` +
`\`${typeComposer.getTypeName()}\`.`
)
}
}
if (
typeComposer instanceof ObjectTypeComposer ||
typeComposer instanceof InterfaceTypeComposer ||
typeComposer instanceof InputTypeComposer
) {
typeComposer.getFieldNames().forEach(fieldName => {
typeComposer.setFieldExtension(fieldName, `createdFrom`, createdFrom)
typeComposer.setFieldExtension(
fieldName,
`plugin`,
plugin ? plugin.name : null
)
if (createdFrom === `sdl`) {
const directives = typeComposer.getFieldDirectives(fieldName)
directives.forEach(({ name, args }) => {
typeComposer.setFieldExtension(fieldName, name, args)
})
}
// Validate field extension args. `graphql-compose` already checks the
// type of directive args in `parseDirectives`, but we want to check
// extensions provided with type builders as well. Also, we warn if an
// extension option was provided which does not exist in the field
// extension definition.
const fieldExtensions = typeComposer.getFieldExtensions(fieldName)
const typeName = typeComposer.getTypeName()
Object.keys(fieldExtensions)
.filter(name => !internalExtensionNames.includes(name))
.forEach(name => {
const args = fieldExtensions[name]
if (!args || typeof args !== `object`) {
report.error(
`Field extension arguments must be provided as an object. ` +
`Received "${args}" on \`${typeName}.${fieldName}\`.`
)
return
}
try {
const definition = schemaComposer.getDirective(name)
// Handle `defaultValue` when not provided as directive
definition.args.forEach(({ name, defaultValue }) => {
if (args[name] === undefined && defaultValue !== undefined) {
args[name] = defaultValue
}
})
Object.keys(args).forEach(arg => {
const argumentDef = definition.args.find(
({ name }) => name === arg
)
if (!argumentDef) {
report.error(
`Field extension \`${name}\` on \`${typeName}.${fieldName}\` ` +
`has invalid argument \`${arg}\`.`
)
return
}
const value = args[arg]
try {
validate(argumentDef.type, value)
} catch (error) {
report.error(
`Field extension \`${name}\` on \`${typeName}.${fieldName}\` ` +
`has argument \`${arg}\` with invalid value "${value}". ` +
error.message
)
}
})
} catch (error) {
report.error(
`Field extension \`${name}\` on \`${typeName}.${fieldName}\` ` +
`is not available.`
)
}
})
})
}
return typeComposer
}
const checkIsAllowedTypeName = name => {
invariant(
name !== `Node`,
`The GraphQL type \`Node\` is reserved for internal use.`
)
invariant(
!name.endsWith(`FilterInput`) && !name.endsWith(`SortInput`),
`GraphQL type names ending with "FilterInput" or "SortInput" are ` +
`reserved for internal use. Please rename \`${name}\`.`
)
invariant(
!builtInScalarTypeNames.includes(name),
`The GraphQL type \`${name}\` is reserved for internal use by ` +
`built-in scalar types.`
)
assertValidName(name)
}
const createTypeComposerFromGatsbyType = ({
schemaComposer,
type,
parentSpan,
}) => {
let typeComposer
switch (type.kind) {
case GatsbyGraphQLTypeKind.OBJECT: {
typeComposer = ObjectTypeComposer.createTemp({
...type.config,
fields: () =>
schemaComposer.typeMapper.convertOutputFieldConfigMap(
type.config.fields
),
interfaces: () => {
if (type.config.interfaces) {
return type.config.interfaces.map(iface => {
if (typeof iface === `string`) {
// Sadly, graphql-compose runs this function too early - before we have
// all of those interfaces actually created in the schema, so have to create
// a temporary placeholder composer :/
if (!schemaComposer.has(iface)) {
const tmpComposer = schemaComposer.createInterfaceTC(iface)
tmpComposer.setExtension(`isPlaceholder`, true)
return tmpComposer
}
return schemaComposer.getIFTC(iface)
} else {
return iface
}
})
} else {
return []
}
},
})
break
}
case GatsbyGraphQLTypeKind.INPUT_OBJECT: {
typeComposer = InputTypeComposer.createTemp({
...type.config,
fields: schemaComposer.typeMapper.convertInputFieldConfigMap(
type.config.fields
),
})
break
}
case GatsbyGraphQLTypeKind.UNION: {
typeComposer = UnionTypeComposer.createTemp({
...type.config,
types: () => {
if (type.config.types) {
return type.config.types.map(typeName => {
if (!schemaComposer.has(typeName)) {
// Sadly, graphql-compose runs this function too early - before we have
// all of those types actually created in the schema, so have to create
// a temporary placeholder composer :/
const tmpComposer = schemaComposer.createObjectTC(typeName)
tmpComposer.setExtension(`isPlaceholder`, true)
return tmpComposer
}
return schemaComposer.getOTC(typeName)
})
} else {
return []
}
},
})
break
}
case GatsbyGraphQLTypeKind.INTERFACE: {
typeComposer = InterfaceTypeComposer.createTemp({
...type.config,
fields: () =>
schemaComposer.typeMapper.convertOutputFieldConfigMap(
type.config.fields
),
interfaces: () => {
if (type.config.interfaces) {
return type.config.interfaces.map(iface => {
if (typeof iface === `string`) {
// Sadly, graphql-compose runs this function too early - before we have
// all of those interfaces actually created in the schema, so have to create
// a temporary placeholder composer :/
if (!schemaComposer.has(iface)) {
const tmpComposer = schemaComposer.createInterfaceTC(iface)
tmpComposer.setExtension(`isPlaceholder`, true)
return tmpComposer
}
return schemaComposer.getIFTC(iface)
} else {
return iface
}
})
} else {
return []
}
},
})
break
}
case GatsbyGraphQLTypeKind.ENUM: {
typeComposer = EnumTypeComposer.createTemp(type.config)
break
}
case GatsbyGraphQLTypeKind.SCALAR: {
typeComposer = ScalarTypeComposer.createTemp(type.config)
break
}
default: {
report.warn(`Illegal type definition: ${JSON.stringify(type.config)}`)
typeComposer = null
}
}
if (typeComposer) {
// Workaround for https://github.com/graphql-compose/graphql-compose/issues/311
typeComposer.schemaComposer = schemaComposer
}
return typeComposer
}
const addSetFieldsOnGraphQLNodeTypeFields = ({ schemaComposer, parentSpan }) =>
Promise.all(
Array.from(schemaComposer.values()).map(async tc => {
if (tc instanceof ObjectTypeComposer && tc.hasInterface(`Node`)) {
const typeName = tc.getTypeName()
const result = await apiRunner(`setFieldsOnGraphQLNodeType`, {
type: {
name: typeName,
get nodes() {
// TODO STRICT_MODE: return iterator instead of array
return getNodesByType(typeName)
},
},
traceId: `initial-setFieldsOnGraphQLNodeType`,
parentSpan,
})
if (result) {
// NOTE: `setFieldsOnGraphQLNodeType` only allows setting
// nested fields with a path as property name, i.e.
// `{ 'frontmatter.published': 'Boolean' }`, but not in the form
// `{ frontmatter: { published: 'Boolean' }}`
result.forEach(fields => tc.addNestedFields(fields))
}
}
})
)
const addThirdPartySchemas = ({
schemaComposer,
thirdPartySchemas,
parentSpan,
}) => {
thirdPartySchemas.forEach(schema => {
const schemaQueryType = schema.getQueryType()
const queryTC = schemaComposer.createTempTC(schemaQueryType)
processThirdPartyTypeFields({
typeComposer: queryTC,
type: schemaQueryType,
schemaQueryType,
})
schemaComposer.Query.addFields(queryTC.getFields())
// Explicitly add the third-party schema's types, so they can be targeted
// in `createResolvers` API.
const types = schema.getTypeMap()
Object.keys(types).forEach(typeName => {
const type = types[typeName]
if (
type !== schemaQueryType &&
!isSpecifiedScalarType(type) &&
!isIntrospectionType(type) &&
type.name !== `Date` &&
type.name !== `JSON`
) {
const typeHasFields =
type instanceof GraphQLObjectType ||
type instanceof GraphQLInterfaceType
// Workaround for an edge case typical for Relay Classic-compatible schemas.
// For example, GitHub API contains this piece:
// type Query { relay: Query }
// And gatsby-source-graphql transforms it to:
// type Query { github: GitHub }
// type GitHub { relay: Query }
// The problem:
// schemaComposer.createTC(type) for type `GitHub` will eagerly create type composers
// for all fields (including `relay` and it's type: `Query` of the third-party schema)
// This unexpected `Query` composer messes up with our own Query type composer and produces duplicate types.
// The workaround is to make sure fields of the GitHub type are lazy and are evaluated only when
// this Query type is already replaced with our own root `Query` type (see processThirdPartyTypeFields):
if (typeHasFields && typeof type._fields === `object`) {
const fields = type._fields
type._fields = () => fields
}
// ^^^ workaround done
const typeComposer = schemaComposer.createTC(type)
if (typeHasFields) {
processThirdPartyTypeFields({
typeComposer,
type,
schemaQueryType,
})
}
typeComposer.setExtension(`createdFrom`, `thirdPartySchema`)
schemaComposer.addSchemaMustHaveType(typeComposer)
}
})
})
}
const resetOverriddenThirdPartyTypeFields = ({ typeComposer }) => {
// The problem: createResolvers API mutates third party schema instance.
// For example it can add a new field referencing a type from our main schema
// Then if we rebuild the schema this old type instance will sneak into
// the new schema and produce the famous error:
// "Schema must contain uniquely named types but contains multiple types named X"
// This function only affects schema rebuilding pathway.
// It cleans up artifacts created by the `createResolvers` API of the previous build
// so that we return the third party schema to its initial state (hence can safely re-add)
// TODO: the right way to fix this would be not to mutate the third party schema in
// the first place. But unfortunately mutation happens in the `graphql-compose`
// and we don't have an easy way to avoid it without major rework
typeComposer.getFieldNames().forEach(fieldName => {
const createdFrom = typeComposer.getFieldExtension(fieldName, `createdFrom`)
if (createdFrom === `createResolvers`) {
typeComposer.removeField(fieldName)
return
}
const config = typeComposer.getFieldExtension(
fieldName,
`originalFieldConfig`
)
if (config) {
typeComposer.removeField(fieldName)
typeComposer.addFields({
[fieldName]: config,
})
}
})
}
const processThirdPartyTypeFields = ({
typeComposer,
type,
schemaQueryType,
}) => {
// Fix for types that refer to Query. Thanks Relay Classic!
const fields = type.getFields()
Object.keys(fields).forEach(fieldName => {
// Remove customization that we could have added via `createResolvers`
// to make it work with schema rebuilding
const fieldType = String(fields[fieldName].type)
if (fieldType.replace(/[[\]!]/g, ``) === schemaQueryType.name) {
typeComposer.extendField(fieldName, {
type: fieldType.replace(schemaQueryType.name, `Query`),
})
}
})
resetOverriddenThirdPartyTypeFields({ typeComposer })
}
const addCustomResolveFunctions = async ({ schemaComposer, parentSpan }) => {
const intermediateSchema = schemaComposer.buildSchema()
const createResolvers = (
resolvers,
{ ignoreNonexistentTypes = false } = {}
) => {
Object.keys(resolvers).forEach(typeName => {
const fields = resolvers[typeName]
if (schemaComposer.has(typeName)) {
const tc = schemaComposer.getOTC(typeName)
Object.keys(fields).forEach(fieldName => {
const fieldConfig = fields[fieldName]
if (tc.hasField(fieldName)) {
const originalFieldConfig = tc.getFieldConfig(fieldName)
const originalTypeName = originalFieldConfig.type.toString()
const originalResolver = originalFieldConfig.resolve
let fieldTypeName
if (fieldConfig.type) {
fieldTypeName = Array.isArray(fieldConfig.type)
? stringifyArray(fieldConfig.type)
: fieldConfig.type.toString()
}
if (
!fieldTypeName ||
fieldTypeName.replace(/!/g, ``) ===
originalTypeName.replace(/!/g, ``) ||
tc.getExtension(`createdFrom`) === `thirdPartySchema`
) {
const newConfig = {}
if (fieldConfig.type) {
newConfig.type = fieldConfig.type
}
if (fieldConfig.args) {
newConfig.args = fieldConfig.args
}
if (fieldConfig.resolve) {
newConfig.resolve = (source, args, context, info) =>
fieldConfig.resolve(source, args, context, {
...info,
originalResolver:
originalResolver || context.defaultFieldResolver,
})
tc.extendFieldExtensions(fieldName, {
needsResolve: true,
})
}
tc.extendField(fieldName, newConfig)
// See resetOverriddenThirdPartyTypeFields for explanation
if (tc.getExtension(`createdFrom`) === `thirdPartySchema`) {
tc.setFieldExtension(
fieldName,
`originalFieldConfig`,
originalFieldConfig
)
}
} else if (fieldTypeName) {
report.warn(
`\`createResolvers\` passed resolvers for field ` +
`\`${typeName}.${fieldName}\` with type \`${fieldTypeName}\`. ` +
`Such a field with type \`${originalTypeName}\` already exists ` +
`on the type. Use \`createTypes\` to override type fields.`
)
}
} else {
tc.addFields({
[fieldName]: fieldConfig,
})
// See resetOverriddenThirdPartyTypeFields for explanation
tc.setFieldExtension(fieldName, `createdFrom`, `createResolvers`)
}
})
} else if (!ignoreNonexistentTypes) {
report.warn(
`\`createResolvers\` passed resolvers for type \`${typeName}\` that ` +
`doesn't exist in the schema. Use \`createTypes\` to add the type ` +
`before adding resolvers.`
)
}
})
}
await apiRunner(`createResolvers`, {
intermediateSchema,
createResolvers,
traceId: `initial-createResolvers`,
parentSpan,
})
}
function attachTracingResolver({ schemaComposer }) {
schemaComposer.forEach(typeComposer => {
if (
typeComposer instanceof ObjectTypeComposer ||
typeComposer instanceof InterfaceTypeComposer
) {
typeComposer.getFieldNames().forEach(fieldName => {
const field = typeComposer.getField(fieldName)
const resolver = wrappingResolver(field.resolve || defaultResolver)
typeComposer.extendField(fieldName, {
resolve: resolver,
})
})
}
})
}
const determineSearchableFields = ({ schemaComposer, typeComposer }) => {
typeComposer.getFieldNames().forEach(fieldName => {
const field = typeComposer.getField(fieldName)
const extensions = typeComposer.getFieldExtensions(fieldName)
if (field.resolve) {
if (extensions.dateformat) {
typeComposer.extendFieldExtensions(fieldName, {
searchable: SEARCHABLE_ENUM.SEARCHABLE,
sortable: SORTABLE_ENUM.SORTABLE,
needsResolve: extensions.proxy ? true : false,