/
builder.ts
1582 lines (1480 loc) · 49.9 KB
/
builder.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
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
import {
assertValidName,
defaultFieldResolver,
getNamedType,
GraphQLBoolean,
GraphQLEnumType,
GraphQLEnumValueConfigMap,
GraphQLField,
GraphQLFieldConfig,
GraphQLFieldConfigArgumentMap,
GraphQLFieldConfigMap,
GraphQLFieldResolver,
GraphQLFloat,
GraphQLID,
GraphQLInputFieldConfig,
GraphQLInputFieldConfigMap,
GraphQLInputObjectType,
GraphQLInputType,
GraphQLInt,
GraphQLInterfaceType,
GraphQLList,
GraphQLNamedType,
GraphQLNonNull,
GraphQLObjectType,
GraphQLOutputType,
GraphQLScalarType,
GraphQLSchema,
GraphQLString,
GraphQLType,
GraphQLUnionType,
isInputObjectType,
isInterfaceType,
isLeafType,
isNamedType,
isObjectType,
isOutputType,
isScalarType,
isSchema,
isUnionType,
isWrappingType,
printSchema,
} from 'graphql'
import { arg, ArgsRecord, NexusArgConfig, NexusArgDef } from './definitions/args'
import {
InputDefinitionBlock,
NexusInputFieldDef,
NexusOutputFieldDef,
OutputDefinitionBlock,
} from './definitions/definitionBlocks'
import { EnumTypeConfig } from './definitions/enumType'
import { NexusExtendInputTypeConfig, NexusExtendInputTypeDef } from './definitions/extendInputType'
import { NexusExtendTypeConfig, NexusExtendTypeDef } from './definitions/extendType'
import { NexusInputObjectTypeConfig } from './definitions/inputObjectType'
import {
InterfaceDefinitionBlock,
NexusInterfaceTypeConfig,
NexusInterfaceTypeDef,
} from './definitions/interfaceType'
import {
Implemented,
NexusObjectTypeConfig,
NexusObjectTypeDef,
ObjectDefinitionBlock,
} from './definitions/objectType'
import { NexusScalarExtensions, NexusScalarTypeConfig } from './definitions/scalarType'
import { NexusUnionTypeConfig, UnionDefinitionBlock, UnionMembers } from './definitions/unionType'
import {
AllNexusInputTypeDefs,
AllNexusNamedTypeDefs,
AllNexusOutputTypeDefs,
isNexusArgDef,
isNexusDynamicInputMethod,
isNexusDynamicOutputMethod,
isNexusDynamicOutputProperty,
isNexusEnumTypeDef,
isNexusExtendInputTypeDef,
isNexusExtendTypeDef,
isNexusInputObjectTypeDef,
isNexusInterfaceTypeDef,
isNexusNamedTypeDef,
isNexusObjectTypeDef,
isNexusPlugin,
isNexusScalarTypeDef,
isNexusUnionTypeDef,
} from './definitions/wrapping'
import {
GraphQLPossibleInputs,
GraphQLPossibleOutputs,
MissingType,
NexusGraphQLFieldConfig,
NexusGraphQLInputObjectTypeConfig,
NexusGraphQLInterfaceTypeConfig,
NexusGraphQLObjectTypeConfig,
NexusGraphQLSchema,
NonNullConfig,
RootTypings,
} from './definitions/_types'
import { DynamicInputMethodDef, DynamicOutputMethodDef } from './dynamicMethod'
import { DynamicOutputPropertyDef } from './dynamicProperty'
import {
NexusFieldExtension,
NexusInputObjectTypeExtension,
NexusInterfaceTypeExtension,
NexusObjectTypeExtension,
NexusSchemaExtension,
} from './extensions'
import {
composeMiddlewareFns,
CreateFieldResolverInfo,
MiddlewareFn,
NexusPlugin,
PluginConfig,
} from './plugin'
import { fieldAuthorizePlugin } from './plugins/fieldAuthorizePlugin'
import { TypegenAutoConfigOptions } from './typegenAutoConfig'
import { TypegenFormatFn } from './typegenFormatPrettier'
import { TypegenMetadata } from './typegenMetadata'
import { AbstractTypeResolver, AllInputTypes, GetGen } from './typegenTypeHelpers'
import { resolveTypegenConfig } from './typegenUtils'
import {
assertNoMissingTypes,
casesHandled,
consoleWarn,
eachObj,
firstDefined,
isObject,
mapValues,
objValues,
UNKNOWN_TYPE_SCALAR,
validateOnInstallHookResult,
} from './utils'
type NexusShapedOutput = {
name: string
definition: (t: ObjectDefinitionBlock<string>) => void
}
type NexusShapedInput = {
name: string
definition: (t: InputDefinitionBlock<string>) => void
}
const SCALARS: Record<string, GraphQLScalarType> = {
String: GraphQLString,
Int: GraphQLInt,
Float: GraphQLFloat,
ID: GraphQLID,
Boolean: GraphQLBoolean,
}
export interface BuilderConfig {
/**
* Generated artifact settings. Set to false to disable all.
* Set to true to enable all and use default paths. Leave
* undefined for default behaviour of each artifact.
*/
outputs?:
| boolean
| {
/**
* TypeScript declaration file generation settings. This file
* contains types reflected off your source code. It is how
* Nexus imbues dynamic code with static guarnatees.
*
* Defaults to being enabled when `process.env.NODE_ENV !== "production"`.
* Set to true to enable and emit into default path (see below).
* Set to false to disable. Set to a string to specify absolute path.
*
* The default path is node_modules/@types/nexus-typegen/index.d.ts.
* This is chosen becuase TypeScript will pick it up without
* any configuration needed by you. For more details about the @types
* system refer to https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types
*/
typegen?: boolean | string
/**
* GraphQL SDL generation settings. This file is not necessary but
* may be nice for teams wishing to review SDL in pull-requests or
* just generally transitioning from a schema-first workflow.
*
* Defaults to false (disabled). Set to true to enable and emit into
* default path (current working directory). Set to a string to specify
* absolute path.
*/
schema?: boolean | string
}
/**
* Whether the schema & types are generated when the server
* starts. Default is !process.env.NODE_ENV || process.env.NODE_ENV === "development"
*/
shouldGenerateArtifacts?: boolean
/**
* Automatically configure type resolution for the TypeScript
* representations of the associated types.
*
* Alias for typegenConfig: typegenAutoConfig(options)
*/
typegenAutoConfig?: TypegenAutoConfigOptions
/**
* A configuration function for advanced cases where
* more control over the `TypegenInfo` is needed.
*/
typegenConfig?: (schema: GraphQLSchema, outputPath: string) => TypegenInfo | PromiseLike<TypegenInfo>
/**
* Adjust the Prettier options used while running prettier over
* the generated output.
*
* Can be an absolute path to a Prettier config file like
* .prettierrc or package.json with "prettier" field, or an object
* of Prettier options.
*
* If provided, you must have prettier available as an importable dep
* in your project.
*
*/
prettierConfig?: string | object
/**
* Manually apply a formatter to the generated content before saving,
* see the `prettierConfig` option if you want to use Prettier.
*/
formatTypegen?: TypegenFormatFn
/**
* Configures the default "nonNullDefaults" for the entire schema the type.
* Read more about how nexus handles nullability
*/
nonNullDefaults?: NonNullConfig
/**
* List of plugins to apply to Nexus, with before/after hooks
* executed first to last: before -> resolve -> after
*/
plugins?: NexusPlugin[]
/**
* Provide if you wish to customize the behavior of the schema printing.
* Otherwise, uses `printSchema` from graphql-js
*/
customPrintSchemaFn?: typeof printSchema
}
export type SchemaConfig = BuilderConfig & {
/**
* All of the GraphQL types. This is an any for simplicity of developer experience,
* if it's an object we get the values, if it's an array we flatten out the
* valid types, ignoring invalid ones.
*/
types: any
/**
* Whether we should process.exit after the artifacts are generated.
* Useful if you wish to explicitly generate the test artifacts at a certain stage in
* a startup or build process.
* @default false
*/
shouldExitAfterGenerateArtifacts?: boolean
} & NexusGenPluginSchemaConfig
export interface TypegenInfo {
/**
* Headers attached to the generate type output
*/
headers: string[]
/**
* All imports for the backing types / context
*/
imports: string[]
/**
* A map of all GraphQL types and what TypeScript types they should
* be represented by.
*/
backingTypeMap: { [K in GetGen<'objectNames'>]?: string }
/**
* The type of the context for the resolvers
*/
contextType?: string
/**
* The path to the @nexus/schema package.
*
* @default '@nexus/schema'
*
* @remarks
*
* This setting is particularly useful when @nexus/schema is being wrapped by
* another library/framework such that @nexus/schema is not expected to be a
* direct dependency at the application level.
*/
nexusSchemaImportId?: string
}
export type TypeToWalk =
| { type: 'named'; value: GraphQLNamedType }
| { type: 'input'; value: NexusShapedInput }
| { type: 'object'; value: NexusShapedOutput }
| { type: 'interface'; value: NexusInterfaceTypeConfig<any> }
export type DynamicInputFields = Record<string, DynamicInputMethodDef<string> | string>
export type DynamicOutputFields = Record<string, DynamicOutputMethodDef<string> | string>
export type DynamicOutputProperties = Record<string, DynamicOutputPropertyDef<string>>
export type TypeDef =
| GraphQLNamedType
| AllNexusNamedTypeDefs
| NexusExtendInputTypeDef<string>
| NexusExtendTypeDef<string>
export type DynamicBlockDef =
| DynamicInputMethodDef<string>
| DynamicOutputMethodDef<string>
| DynamicOutputPropertyDef<string>
export type NexusAcceptedTypeDef = TypeDef | DynamicBlockDef
export type PluginBuilderLens = {
hasType: SchemaBuilder['hasType']
addType: SchemaBuilder['addType']
setConfigOption: SchemaBuilder['setConfigOption']
hasConfigOption: SchemaBuilder['hasConfigOption']
getConfigOption: SchemaBuilder['getConfigOption']
}
/**
* Builds all of the types, properly accounts for any using "mix".
* Since the enum types are resolved synchronously, these need to guard for
* circular references at this step, while fields will guard for it during lazy evaluation.
*/
export class SchemaBuilder {
/**
* Used to check for circular references.
*/
protected buildingTypes = new Set()
/**
* The "final type" map contains all types as they are built.
*/
protected finalTypeMap: Record<string, GraphQLNamedType> = {}
/**
* The "defined type" map keeps track of all of the types that were
* defined directly as `GraphQL*Type` objects, so we don't accidentally
* overwrite any.
*/
protected definedTypeMap: Record<string, GraphQLNamedType> = {}
/**
* The "pending type" map keeps track of all types that were defined w/
* GraphQL Nexus and haven't been processed into concrete types yet.
*/
protected pendingTypeMap: Record<string, AllNexusNamedTypeDefs> = {}
/**
* All "extensions" to types (adding fields on types from many locations)
*/
protected typeExtendMap: Record<string, NexusExtendTypeConfig<string>[] | null> = {}
/**
* All "extensions" to input types (adding fields on types from many locations)
*/
protected inputTypeExtendMap: Record<string, NexusExtendInputTypeConfig<string>[] | null> = {}
/**
* Configures the root-level nonNullDefaults defaults
*/
protected nonNullDefaults: NonNullConfig = {}
protected dynamicInputFields: DynamicInputFields = {}
protected dynamicOutputFields: DynamicOutputFields = {}
protected dynamicOutputProperties: DynamicOutputProperties = {}
protected plugins: NexusPlugin[] = []
/**
* All types that need to be traversed for children types
*/
protected typesToWalk: TypeToWalk[] = []
/**
* Root type mapping information annotated on the type definitions
*/
protected rootTypings: RootTypings = {}
/**
* Array of missing types
*/
protected missingTypes: Record<string, MissingType> = {}
/**
* Methods we are able to access to read/modify builder state from plugins
*/
protected builderLens: PluginBuilderLens
/**
* Created just before types are walked, this keeps track of all of the resolvers
*/
protected onMissingTypeFns: Exclude<PluginConfig['onMissingType'], undefined>[] = []
/**
* Executed just before types are walked
*/
protected onBeforeBuildFns: Exclude<PluginConfig['onBeforeBuild'], undefined>[] = []
/**
* Executed as the field resolvers are included on the field
*/
protected onCreateResolverFns: Exclude<PluginConfig['onCreateFieldResolver'], undefined>[] = []
/**
* Executed as the field "subscribe" fields are included on the schema
*/
protected onCreateSubscribeFns: Exclude<PluginConfig['onCreateFieldSubscribe'], undefined>[] = []
/**
* Executed after the schema is constructed, for any final verification
*/
protected onAfterBuildFns: Exclude<PluginConfig['onAfterBuild'], undefined>[] = []
/**
* The `schemaExtension` is created just after the types are walked,
* but before the fields are materialized.
*/
protected _schemaExtension?: NexusSchemaExtension
get schemaExtension() {
/* istanbul ignore next */
if (!this._schemaExtension) {
throw new Error('Cannot reference schemaExtension before it is created')
}
return this._schemaExtension
}
constructor(protected config: BuilderConfig) {
this.nonNullDefaults = {
input: false,
output: false,
...config.nonNullDefaults,
}
this.plugins = config.plugins || [fieldAuthorizePlugin()]
this.builderLens = Object.freeze({
hasType: this.hasType,
addType: this.addType,
setConfigOption: this.setConfigOption,
hasConfigOption: this.hasConfigOption,
getConfigOption: this.getConfigOption,
})
}
setConfigOption = <K extends keyof BuilderConfig>(key: K, value: BuilderConfig[K]) => {
this.config = {
...this.config,
[key]: value,
}
}
hasConfigOption = (key: keyof BuilderConfig): boolean => {
return this.config.hasOwnProperty(key)
}
getConfigOption = <K extends keyof BuilderConfig>(key: K): BuilderConfig[K] => {
return this.config[key]
}
hasType = (typeName: string): boolean => {
return Boolean(this.pendingTypeMap[typeName] || this.finalTypeMap[typeName])
}
/**
* Add type takes a Nexus type, or a GraphQL type and pulls
* it into an internal "type registry". It also does an initial pass
* on any types that are referenced on the "types" field and pulls
* those in too, so you can define types anonymously, without
* exporting them.
*/
addType = (typeDef: TypeDef | DynamicBlockDef) => {
if (isNexusDynamicInputMethod(typeDef)) {
this.dynamicInputFields[typeDef.name] = typeDef
return
}
if (isNexusDynamicOutputMethod(typeDef)) {
this.dynamicOutputFields[typeDef.name] = typeDef
return
}
if (isNexusDynamicOutputProperty(typeDef)) {
this.dynamicOutputProperties[typeDef.name] = typeDef
return
}
// Don't worry about internal types.
if (typeDef.name?.indexOf('__') === 0) {
return
}
const existingType = this.definedTypeMap[typeDef.name] || this.pendingTypeMap[typeDef.name]
if (isNexusExtendTypeDef(typeDef)) {
const typeExtensions = (this.typeExtendMap[typeDef.name] = this.typeExtendMap[typeDef.name] || [])
typeExtensions.push(typeDef.value)
this.typesToWalk.push({ type: 'object', value: typeDef.value })
return
}
if (isNexusExtendInputTypeDef(typeDef)) {
const typeExtensions = (this.inputTypeExtendMap[typeDef.name] =
this.inputTypeExtendMap[typeDef.name] || [])
typeExtensions.push(typeDef.value)
this.typesToWalk.push({ type: 'input', value: typeDef.value })
return
}
if (existingType) {
// Allow importing the same exact type more than once.
if (existingType === typeDef) {
return
}
throw extendError(typeDef.name)
}
if (isNexusScalarTypeDef(typeDef) && typeDef.value.asNexusMethod) {
this.dynamicInputFields[typeDef.value.asNexusMethod] = typeDef.name
this.dynamicOutputFields[typeDef.value.asNexusMethod] = typeDef.name
if (typeDef.value.rootTyping) {
this.rootTypings[typeDef.name] = typeDef.value.rootTyping
}
} else if (isScalarType(typeDef)) {
const scalarDef = typeDef as GraphQLScalarType & {
extensions?: NexusScalarExtensions
}
if (scalarDef.extensions && scalarDef.extensions.nexus) {
const { asNexusMethod, rootTyping } = scalarDef.extensions.nexus
if (asNexusMethod) {
this.dynamicInputFields[asNexusMethod] = scalarDef.name
this.dynamicOutputFields[asNexusMethod] = typeDef.name
}
if (rootTyping) {
this.rootTypings[scalarDef.name] = rootTyping
}
}
}
if (isNamedType(typeDef)) {
let finalTypeDef = typeDef
if (isObjectType(typeDef)) {
const config = typeDef.toConfig()
finalTypeDef = new GraphQLObjectType({
...config,
fields: () => this.rebuildNamedOutputFields(config),
interfaces: () => config.interfaces.map((t) => this.getInterface(t.name)),
})
} else if (isInterfaceType(typeDef)) {
const config = typeDef.toConfig()
finalTypeDef = new GraphQLInterfaceType({
...config,
fields: () => this.rebuildNamedOutputFields(config),
})
} else if (isUnionType(typeDef)) {
const config = typeDef.toConfig()
finalTypeDef = new GraphQLUnionType({
...config,
types: () => config.types.map((t) => this.getObjectType(t.name)),
})
}
this.finalTypeMap[typeDef.name] = finalTypeDef
this.definedTypeMap[typeDef.name] = typeDef
this.typesToWalk.push({ type: 'named', value: typeDef })
} else {
this.pendingTypeMap[typeDef.name] = typeDef
}
if (isNexusInputObjectTypeDef(typeDef)) {
this.typesToWalk.push({ type: 'input', value: typeDef.value })
}
if (isNexusObjectTypeDef(typeDef)) {
this.typesToWalk.push({ type: 'object', value: typeDef.value })
}
if (isNexusInterfaceTypeDef(typeDef)) {
this.typesToWalk.push({ type: 'interface', value: typeDef.value })
}
}
addTypes(types: any) {
if (!types) {
return
}
if (isSchema(types)) {
this.addTypes(types.getTypeMap())
}
if (isNexusPlugin(types)) {
if (!this.config.plugins?.includes(types)) {
throw new Error(
`Nexus plugin ${types.config.name} was seen in the "types" config, but should instead be provided to the "plugins" array.`
)
}
return
}
if (
isNexusNamedTypeDef(types) ||
isNexusExtendTypeDef(types) ||
isNexusExtendInputTypeDef(types) ||
isNamedType(types) ||
isNexusDynamicInputMethod(types) ||
isNexusDynamicOutputMethod(types) ||
isNexusDynamicOutputProperty(types)
) {
this.addType(types)
} else if (Array.isArray(types)) {
types.forEach((typeDef) => this.addTypes(typeDef))
} else if (isObject(types)) {
Object.keys(types).forEach((key) => this.addTypes(types[key]))
}
}
rebuildNamedOutputFields(
config: ReturnType<GraphQLObjectType['toConfig'] | GraphQLInterfaceType['toConfig']>
) {
const { fields, ...rest } = config
const fieldsConfig = typeof fields === 'function' ? fields() : fields
return mapValues(fieldsConfig, (val, key) => {
const { resolve, type, ...fieldConfig } = val
const finalType = this.replaceNamedType(type)
return {
...fieldConfig,
type: finalType,
resolve: this.makeFinalResolver(
{
builder: this.builderLens,
fieldConfig: {
...fieldConfig,
type: finalType,
name: key,
},
schemaConfig: this.config,
parentTypeConfig: rest,
schemaExtension: this.schemaExtension,
},
resolve
),
}
})
}
walkTypes() {
let obj
while ((obj = this.typesToWalk.shift())) {
switch (obj.type) {
case 'input':
this.walkInputType(obj.value)
break
case 'interface':
this.walkInterfaceType(obj.value)
break
case 'named':
this.walkNamedTypes(obj.value)
break
case 'object':
this.walkOutputType(obj.value)
break
default:
casesHandled(obj)
}
}
}
beforeWalkTypes() {
this.plugins.forEach((obj, i) => {
if (!isNexusPlugin(obj)) {
throw new Error(`Expected a plugin in plugins[${i}], saw ${obj}`)
}
const { config: pluginConfig } = obj
if (pluginConfig.onInstall) {
const installResult = pluginConfig.onInstall(this.builderLens)
validateOnInstallHookResult(pluginConfig.name, installResult)
installResult.types.forEach((t) => this.addType(t))
}
if (pluginConfig.onCreateFieldResolver) {
this.onCreateResolverFns.push(pluginConfig.onCreateFieldResolver)
}
if (pluginConfig.onCreateFieldSubscribe) {
this.onCreateSubscribeFns.push(pluginConfig.onCreateFieldSubscribe)
}
if (pluginConfig.onBeforeBuild) {
this.onBeforeBuildFns.push(pluginConfig.onBeforeBuild)
}
if (pluginConfig.onMissingType) {
this.onMissingTypeFns.push(pluginConfig.onMissingType)
}
if (pluginConfig.onAfterBuild) {
this.onAfterBuildFns.push(pluginConfig.onAfterBuild)
}
})
}
beforeBuildTypes() {
this.onBeforeBuildFns.forEach((fn) => {
fn(this.builderLens)
if (this.typesToWalk.length > 0) {
this.walkTypes()
}
})
}
buildNexusTypes() {
// If Query isn't defined, set it to null so it falls through to "missingType"
if (!this.pendingTypeMap.Query) {
this.pendingTypeMap.Query = null as any
}
Object.keys(this.pendingTypeMap).forEach((key) => {
if (this.typesToWalk.length > 0) {
this.walkTypes()
}
// If we've already constructed the type by this point,
// via circular dependency resolution don't worry about building it.
if (this.finalTypeMap[key]) {
return
}
if (this.definedTypeMap[key]) {
throw extendError(key)
}
this.finalTypeMap[key] = this.getOrBuildType(key)
this.buildingTypes.clear()
})
Object.keys(this.typeExtendMap).forEach((key) => {
// If we haven't defined the type, assume it's an object type
if (this.typeExtendMap[key] !== null) {
this.buildObjectType({
name: key,
definition() {},
})
}
})
Object.keys(this.inputTypeExtendMap).forEach((key) => {
// If we haven't defined the type, assume it's an input object type
if (this.inputTypeExtendMap[key] !== null) {
this.buildInputObjectType({
name: key,
definition() {},
})
}
})
}
createSchemaExtension() {
this._schemaExtension = new NexusSchemaExtension({
...this.config,
dynamicFields: {
dynamicInputFields: this.dynamicInputFields,
dynamicOutputFields: this.dynamicOutputFields,
dynamicOutputProperties: this.dynamicOutputProperties,
},
rootTypings: this.rootTypings,
})
}
getFinalTypeMap(): BuildTypes<any> {
this.beforeWalkTypes()
this.createSchemaExtension()
this.walkTypes()
this.beforeBuildTypes()
this.buildNexusTypes()
return {
finalConfig: this.config,
typeMap: this.finalTypeMap,
schemaExtension: this.schemaExtension!,
missingTypes: this.missingTypes,
onAfterBuildFns: this.onAfterBuildFns,
}
}
buildInputObjectType(config: NexusInputObjectTypeConfig<any>): GraphQLInputObjectType {
const fields: NexusInputFieldDef[] = []
const definitionBlock = new InputDefinitionBlock({
typeName: config.name,
addField: (field) => fields.push(field),
addDynamicInputFields: (block, isList) => this.addDynamicInputFields(block, isList),
warn: consoleWarn,
})
config.definition(definitionBlock)
const extensions = this.inputTypeExtendMap[config.name]
if (extensions) {
extensions.forEach((extension) => {
extension.definition(definitionBlock)
})
}
this.inputTypeExtendMap[config.name] = null
const inputObjectTypeConfig: NexusGraphQLInputObjectTypeConfig = {
name: config.name,
fields: () => this.buildInputObjectFields(fields, inputObjectTypeConfig),
description: config.description,
extensions: {
nexus: new NexusInputObjectTypeExtension(config),
},
}
return this.finalize(new GraphQLInputObjectType(inputObjectTypeConfig))
}
buildObjectType(config: NexusObjectTypeConfig<any>) {
const fields: NexusOutputFieldDef[] = []
const interfaces: Implemented[] = []
const definitionBlock = new ObjectDefinitionBlock({
typeName: config.name,
addField: (fieldDef) => fields.push(fieldDef),
addInterfaces: (interfaceDefs) => interfaces.push(...interfaceDefs),
addDynamicOutputMembers: (block, isList) => this.addDynamicOutputMembers(block, isList, 'build'),
warn: consoleWarn,
})
config.definition(definitionBlock)
const extensions = this.typeExtendMap[config.name]
if (extensions) {
extensions.forEach((extension) => {
extension.definition(definitionBlock)
})
}
this.typeExtendMap[config.name] = null
if (config.rootTyping) {
this.rootTypings[config.name] = config.rootTyping
}
const objectTypeConfig: NexusGraphQLObjectTypeConfig = {
name: config.name,
interfaces: () => interfaces.map((i) => this.getInterface(i)),
description: config.description,
fields: () => {
const allInterfaces = interfaces.map((i) => this.getInterface(i))
const interfaceConfigs = allInterfaces.map((i) => i.toConfig())
const interfaceFieldsMap: GraphQLFieldConfigMap<any, any> = {}
interfaceConfigs.forEach((i) => {
Object.keys(i.fields).forEach((iFieldName) => {
interfaceFieldsMap[iFieldName] = i.fields[iFieldName]
})
})
return this.buildOutputFields(fields, objectTypeConfig, interfaceFieldsMap)
},
extensions: {
nexus: new NexusObjectTypeExtension(config),
},
}
return this.finalize(new GraphQLObjectType(objectTypeConfig))
}
buildInterfaceType(config: NexusInterfaceTypeConfig<any>) {
const { name, description } = config
let resolveType: AbstractTypeResolver<string> | undefined
const fields: NexusOutputFieldDef[] = []
const definitionBlock = new InterfaceDefinitionBlock({
typeName: config.name,
addField: (field) => fields.push(field),
setResolveType: (fn) => (resolveType = fn),
addDynamicOutputMembers: (block, isList) => this.addDynamicOutputMembers(block, isList, 'build'),
warn: consoleWarn,
})
config.definition(definitionBlock)
const toExtend = this.typeExtendMap[config.name]
if (toExtend) {
toExtend.forEach((e) => {
e.definition(definitionBlock)
})
}
if (!resolveType) {
resolveType = this.missingResolveType(config.name, 'interface')
}
if (config.rootTyping) {
this.rootTypings[config.name] = config.rootTyping
}
const interfaceTypeConfig: NexusGraphQLInterfaceTypeConfig = {
name,
resolveType,
description,
fields: () => this.buildOutputFields(fields, interfaceTypeConfig, {}),
extensions: {
nexus: new NexusInterfaceTypeExtension(config),
},
}
return this.finalize(new GraphQLInterfaceType(interfaceTypeConfig))
}
buildEnumType(config: EnumTypeConfig<any>) {
const { members } = config
const values: GraphQLEnumValueConfigMap = {}
if (Array.isArray(members)) {
members.forEach((m) => {
if (typeof m === 'string') {
values[m] = { value: m }
} else {
values[m.name] = {
value: typeof m.value === 'undefined' ? m.name : m.value,
deprecationReason: m.deprecation,
description: m.description,
}
}
})
} else {
Object.keys(members)
// members can potentially be a TypeScript enum.
// The compiled version of this enum will be the members object,
// numeric enums members also get a reverse mapping from enum values to enum names.
// In these cases we have to ensure we don't include these reverse mapping keys.
// See: https://www.typescriptlang.org/docs/handbook/enums.html
.filter((key) => isNaN(+key))
.forEach((key) => {
assertValidName(key)
values[key] = {
value: (members as Record<string, string | number | symbol>)[key],
}
})
}
if (!Object.keys(values).length) {
throw new Error(`GraphQL Nexus: Enum ${config.name} must have at least one member`)
}
if (config.rootTyping) {
this.rootTypings[config.name] = config.rootTyping
}
return this.finalize(
new GraphQLEnumType({
name: config.name,
values: values,
description: config.description,
})
)
}
buildUnionType(config: NexusUnionTypeConfig<any>) {
let members: UnionMembers | undefined
let resolveType: AbstractTypeResolver<string> | undefined
config.definition(
new UnionDefinitionBlock({
setResolveType: (fn) => (resolveType = fn),
addUnionMembers: (unionMembers) => (members = unionMembers),
})
)
if (!resolveType) {
resolveType = this.missingResolveType(config.name, 'union')
}
if (config.rootTyping) {
this.rootTypings[config.name] = config.rootTyping
}
return this.finalize(
new GraphQLUnionType({
name: config.name,
resolveType,
description: config.description,
types: () => this.buildUnionMembers(config.name, members),
})
)
}
buildScalarType(config: NexusScalarTypeConfig<string>): GraphQLScalarType {
if (config.rootTyping) {
this.rootTypings[config.name] = config.rootTyping
}
return this.finalize(new GraphQLScalarType(config))
}
protected finalize<T extends GraphQLNamedType>(type: T): T {
this.finalTypeMap[type.name] = type
return type
}
protected missingType(typeName: string, fromObject: boolean = false): GraphQLNamedType {
invariantGuard(typeName)
if (this.onMissingTypeFns.length) {
for (let i = 0; i < this.onMissingTypeFns.length; i++) {
const fn = this.onMissingTypeFns[i]
const replacementType = fn(typeName, this.builderLens)
if (replacementType && replacementType.name) {
this.addType(replacementType)
return this.getOrBuildType(replacementType)
}
}
}
if (typeName === 'Query') {
return new GraphQLObjectType({
name: 'Query',
fields: {
ok: {
type: GraphQLNonNull(GraphQLBoolean),
resolve: () => true,
},
},
})
}
if (!this.missingTypes[typeName]) {
this.missingTypes[typeName] = { fromObject }
}
return UNKNOWN_TYPE_SCALAR
}
protected buildUnionMembers(unionName: string, members: UnionMembers | undefined) {
const unionMembers: GraphQLObjectType[] = []
/* istanbul ignore next */
if (!members) {
throw new Error(
`Missing Union members for ${unionName}.` +
`Make sure to call the t.members(...) method in the union blocks`
)
}
members.forEach((member) => {
unionMembers.push(this.getObjectType(member))
})
/* istanbul ignore next */
if (!unionMembers.length) {
throw new Error(`GraphQL Nexus: Union ${unionName} must have at least one member type`)
}
return unionMembers
}
protected buildOutputFields(
fields: NexusOutputFieldDef[],
typeConfig: NexusGraphQLInterfaceTypeConfig | NexusGraphQLObjectTypeConfig,
intoObject: GraphQLFieldConfigMap<any, any>
) {
fields.forEach((field) => {
intoObject[field.name] = this.buildOutputField(field, typeConfig)