-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathbase-resolvers-visitor.ts
More file actions
2243 lines (2030 loc) · 74.7 KB
/
base-resolvers-visitor.ts
File metadata and controls
2243 lines (2030 loc) · 74.7 KB
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 { ApolloFederation, type FederationMeta, getBaseType } from '@graphql-codegen/plugin-helpers';
import { getRootTypeNames } from '@graphql-tools/utils';
import autoBind from 'auto-bind';
import {
ASTNode,
DirectiveDefinitionNode,
EnumTypeDefinitionNode,
FieldDefinitionNode,
GraphQLInterfaceType,
GraphQLNamedType,
GraphQLObjectType,
GraphQLSchema,
GraphQLUnionType,
InputValueDefinitionNode,
InterfaceTypeDefinitionNode,
isEnumType,
isInterfaceType,
isNonNullType,
isObjectType,
isUnionType,
ListTypeNode,
NamedTypeNode,
NonNullTypeNode,
ObjectTypeDefinitionNode,
ScalarTypeDefinitionNode,
UnionTypeDefinitionNode,
} from 'graphql';
import { BaseVisitor, BaseVisitorConvertOptions, ParsedConfig, RawConfig } from './base-visitor.js';
import { parseEnumValues } from './enum-values.js';
import { buildMapperImport, ExternalParsedMapper, ParsedMapper, parseMapper, transformMappers } from './mappers.js';
import { DEFAULT_SCALARS } from './scalars.js';
import {
AvoidOptionalsConfig,
ConvertOptions,
DeclarationKind,
EnumValuesMap,
NormalizedAvoidOptionalsConfig,
NormalizedScalarsMap,
ParsedEnumValuesMap,
ResolversNonOptionalTypenameConfig,
} from './types.js';
import {
buildScalarsFromConfig,
DeclarationBlock,
DeclarationBlockConfig,
getBaseTypeNode,
getConfigValue,
indent,
OMIT_TYPE,
REQUIRE_FIELDS_TYPE,
stripMapperTypeInterpolation,
wrapTypeWithModifiers,
} from './utils.js';
import { OperationVariablesToObject } from './variables-to-object.js';
import { normalizeAvoidOptionals } from './avoid-optionals.js';
export interface ParsedResolversConfig extends ParsedConfig {
contextType: ParsedMapper;
fieldContextTypes: Array<string>;
directiveContextTypes: Array<string>;
rootValueType: ParsedMapper;
mappers: {
[typeName: string]: ParsedMapper;
};
defaultMapper: ParsedMapper | null;
avoidOptionals: NormalizedAvoidOptionalsConfig;
addUnderscoreToArgsType: boolean;
addInterfaceFieldResolverTypes: boolean;
enumValues: ParsedEnumValuesMap;
resolverTypeWrapperSignature: string;
federation: boolean;
enumPrefix: boolean;
enumSuffix: boolean;
optionalResolveType: boolean;
immutableTypes: boolean;
namespacedImportName: string;
resolverTypeSuffix: string;
allResolversTypeName: string;
internalResolversPrefix: string;
directiveResolverMappings: Record<string, string>;
resolversNonOptionalTypename: ResolversNonOptionalTypenameConfig;
avoidCheckingAbstractTypesRecursively: boolean;
}
export interface FieldDefinitionResult {
node: FieldDefinitionNode;
printContent: FieldDefinitionPrintFn;
}
type FieldDefinitionPrintFn = (
parentNode: ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode,
avoidResolverOptionals: boolean
) => { value: string | null; meta: { federation?: { isResolveReference: boolean } } };
export interface RootResolver {
content: string;
generatedResolverTypes: {
resolversMap: { name: string };
userDefined: Record<
string,
{
name: string;
hasIsTypeOf: boolean;
federation?: { hasResolveReference: boolean };
}
>;
};
}
export interface RawResolversConfig extends RawConfig {
/**
* @description Adds `_` to generated `Args` types in order to avoid duplicate identifiers.
*
* @exampleMarkdown
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* addUnderscoreToArgsType: true
* },
* },
* },
* };
* export default config;
* ```
*
*/
addUnderscoreToArgsType?: boolean;
/**
* @description Use this configuration to set a custom type for your `context`, and it will
* affect all the resolvers, without the need to override it using generics each time.
* If you wish to use an external type and import it from another file, you can use `add` plugin
* and add the required `import` statement, or you can use a `module#type` syntax.
*
* @exampleMarkdown
* ## Custom Context Type
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* contextType: 'MyContext'
* },
* },
* },
* };
* export default config;
* ```
*
* ## Custom Context Type by Path
*
* Note that the path should be relative to the generated file.
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* contextType: './my-types#MyContext'
* },
* },
* },
* };
* export default config;
* ```
*/
contextType?: string;
/**
* @description Use this to set a custom type for a specific field `context`.
* It will only affect the targeted resolvers.
* You can either use `Field.Path#ContextTypeName` or `Field.Path#ExternalFileName#ContextTypeName`
*
* @exampleMarkdown
* ## Custom Field Context Types
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* fieldContextTypes: ['MyType.foo#CustomContextType', 'MyType.bar#./my-file#ContextTypeOne']
* },
* },
* },
* };
* export default config;
* ```
*
*/
fieldContextTypes?: Array<string>;
/**
* @description Use this configuration to set a custom type for the `rootValue`, and it will
* affect resolvers of all root types (Query, Mutation and Subscription), without the need to override it using generics each time.
* If you wish to use an external type and import it from another file, you can use `add` plugin
* and add the required `import` statement, or you can use both `module#type` or `module#namespace#type` syntax.
*
* @exampleMarkdown
* ## Custom RootValue Type
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* rootValueType: 'MyRootValue'
* },
* },
* },
* };
* export default config;
* ```
*
* ## Custom RootValue Type
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* rootValueType: './my-types#MyRootValue'
* },
* },
* },
* };
* export default config;
* ```
*/
rootValueType?: string;
/**
* @description Use this to set a custom type for a specific field `context` decorated by a directive.
* It will only affect the targeted resolvers.
* You can either use `Field.Path#ContextTypeName` or `Field.Path#ExternalFileName#ContextTypeName`
*
* ContextTypeName should by a generic Type that take the context or field context type as only type parameter.
*
* @exampleMarkdown
* ## Directive Context Extender
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* directiveContextTypes: ['myCustomDirectiveName#./my-file#CustomContextExtender']
* },
* },
* },
* };
* export default config;
* ```
*
*/
directiveContextTypes?: Array<string>;
/**
* @description Adds a suffix to the imported names to prevent name clashes.
*
* @exampleMarkdown
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* mapperTypeSuffix: 'Model'
* },
* },
* },
* };
* export default config;
* ```
*/
mapperTypeSuffix?: string;
/**
* @description Replaces a GraphQL type usage with a custom type, allowing you to return custom object from
* your resolvers.
* You can use both `module#type` and `module#namespace#type` syntax.
*
* @exampleMarkdown
* ## Custom Context Type
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* mappers: {
* User: './my-models#UserDbObject',
* Book: './my-models#Collections',
* }
* },
* },
* },
* };
* export default config;
* ```
*/
mappers?: { [typeName: string]: string };
/**
* @description Allow you to set the default mapper when it's not being override by `mappers` or generics.
* You can specify a type name, or specify a string in `module#type` or `module#namespace#type` format.
* The default value of mappers is the TypeScript type generated by `typescript` package.
*
* @exampleMarkdown
* ## Replace with any
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* defaultMapper: 'any',
* },
* },
* },
* };
* export default config;
* ```
*
* ## Custom Base Object
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* defaultMapper: './my-file#BaseObject',
* },
* },
* },
* };
* export default config;
* ```
*
* ## Wrap default types with Partial
*
* You can also specify a custom wrapper for the original type, without overriding the original generated types, use `{T}` to specify the identifier. (for flow, use `$Shape<{T}>`)
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* defaultMapper: 'Partial<{T}>',
* },
* },
* },
* };
* export default config;
* ```
*
* ## Allow deep partial with `utility-types`
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* plugins: ['typescript', 'typescript-resolver', { add: { content: "import { DeepPartial } from 'utility-types';" } }],
* config: {
* defaultMapper: 'DeepPartial<{T}>',
* avoidCheckingAbstractTypesRecursively: true // required if you have complex nested abstract types
* },
* },
* },
* };
* export default config;
* ```
*/
defaultMapper?: string;
/**
* @description This will cause the generator to avoid using optionals (`?`),
* so all field resolvers must be implemented in order to avoid compilation errors.
* @default false
*
* @exampleMarkdown
* ## Override all definition types
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* plugins: ['typescript', 'typescript-resolver'],
* config: {
* avoidOptionals: true
* },
* },
* },
* };
* export default config;
* ```
*
* ## Override only specific definition types
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* plugins: ['typescript', 'typescript-resolver'],
* config: {
* avoidOptionals: {
* field: true,
* inputValue: true,
* object: true,
* defaultValue: true,
* query: true,
* mutation: true,
* subscription: true,
* }
* },
* },
* },
* };
* export default config;
* ```
*/
avoidOptionals?: boolean | AvoidOptionalsConfig;
/**
* @description Warns about unused mappers.
* @default true
*
* @exampleMarkdown
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* plugins: ['typescript', 'typescript-resolver'],
* config: {
* showUnusedMappers: true,
* },
* },
* },
* };
* export default config;
* ```
*/
showUnusedMappers?: boolean;
/**
* @description Overrides the default value of enum values declared in your GraphQL schema, supported
* in this plugin because of the need for integration with `typescript` package.
* See documentation under `typescript` plugin for more information and examples.
*/
enumValues?: EnumValuesMap;
/**
* @default Promise<T> | T
* @description Allow you to override `resolverTypeWrapper` definition.
*/
resolverTypeWrapperSignature?: string;
/**
* @default false
* @description Supports Apollo Federation
*/
federation?: boolean;
/**
* @default true
* @description Allow you to disable prefixing for generated enums, works in combination with `typesPrefix`.
*
* @exampleMarkdown
* ## Disable enum prefixes
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* plugins: ['typescript', 'typescript-resolver'],
* config: {
* typesPrefix: 'I',
* enumPrefix: false
* },
* },
* },
* };
* export default config;
* ```
*/
enumPrefix?: boolean;
/**
* @default true
* @description Allow you to disable suffixing for generated enums, works in combination with `typesSuffix`.
*
* @exampleMarkdown
* ## Disable enum suffixes
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* plugins: ['typescript', 'typescript-resolver'],
* config: {
* typesSuffix: 'I',
* enumSuffix: false
* },
* },
* },
* };
* export default config;
* ```
*/
enumSuffix?: boolean;
/**
* @description Configures behavior for custom directives from various GraphQL libraries.
* @exampleMarkdown
* ## `@semanticNonNull`
* First, install `graphql-sock` peer dependency:
*
* ```sh npm2yarn
* npm install -D graphql-sock
* ```
*
* Now, you can enable support for `@semanticNonNull` directive:
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file.ts': {
* plugins: ['typescript-resolvers'],
* config: {
* customDirectives: {
* semanticNonNull: true
* }
* },
* },
* },
* };
* export default config;
* ```
*/
customDirectives?: {
semanticNonNull?: boolean;
};
/**
* @default false
* @description Sets the `__resolveType` field as optional field.
*/
optionalResolveType?: boolean;
/**
* @default false
* @description Generates immutable types by adding `readonly` to properties and uses `ReadonlyArray`.
*/
immutableTypes?: boolean;
/**
* @default ''
* @description Prefixes all GraphQL related generated types with that value, as namespaces import.
* You can use this feature to allow separation of plugins to different files.
*/
namespacedImportName?: string;
/**
* @default Resolvers
* @description Suffix we add to each generated type resolver.
*/
resolverTypeSuffix?: string;
/**
* @default Resolvers
* @description The type name to use when exporting all resolvers signature as unified type.
*/
allResolversTypeName?: string;
/**
* @type string
* @default '__'
* @description Defines the prefix value used for `__resolveType` and `__isTypeOf` resolvers.
* If you are using `mercurius-js`, please set this field to empty string for better compatibility.
*/
internalResolversPrefix?: string;
/**
* @description Makes `__typename` of resolver mappings non-optional without affecting the base types.
* @default false
*
* @exampleMarkdown
* ## Enable for all
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* plugins: ['typescript', 'typescript-resolver'],
* config: {
* resolversNonOptionalTypename: true // or { unionMember: true, interfaceImplementingType: true }
* },
* },
* },
* };
* export default config;
* ```
*
* ## Enable except for some types
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* plugins: ['typescript', 'typescript-resolver'],
* config: {
* resolversNonOptionalTypename: {
* unionMember: true,
* interfaceImplementingType: true,
* excludeTypes: ['MyType'],
* }
* },
* },
* },
* };
* export default config;
* ```
*/
resolversNonOptionalTypename?: boolean | ResolversNonOptionalTypenameConfig;
/**
* @type boolean
* @default false
* @description If true, recursively goes through all object type's fields, checks if they have abstract types and generates expected types correctly.
* This may not work for cases where provided default mapper types are also nested e.g. `defaultMapper: DeepPartial<{T}>` or `defaultMapper: Partial<{T}>`.
*/
avoidCheckingAbstractTypesRecursively?: boolean;
/**
* @description If true, add field resolver types to Interfaces.
* By default, GraphQL Interfaces do not trigger any field resolvers,
* meaning every implementing type must implement the same resolver for the shared fields.
*
* Some tools provide a way to change the default behaviour by making GraphQL Objects inherit
* missing resolvers from their Interface types. In these cases, it is fine to turn this option to true.
*
* For example, if you are using `@graphql-tools/schema#makeExecutableSchema` with `inheritResolversFromInterfaces: true`,
* you can make `addInterfaceFieldResolverTypes: true` as well
* https://the-guild.dev/graphql/tools/docs/generate-schema#makeexecutableschema
*
* @exampleMarkdown
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* plugins: ['typescript', 'typescript-resolver'],
* config: {
* addInterfaceFieldResolverTypes: true,
* },
* },
* },
* };
* export default config;
* ```
*
* @type boolean
* @default false
*/
addInterfaceFieldResolverTypes?: boolean;
/**
* @ignore
*/
directiveResolverMappings?: Record<string, string>;
}
export type ResolverTypes = { [gqlType: string]: string };
export type ResolverParentTypes = { [gqlType: string]: string };
export type GroupedMappers = Record<string, { identifier: string; asDefault?: boolean }[]>;
type FieldContextTypeMap = Record<string, ParsedMapper>;
export class BaseResolversVisitor<
TRawConfig extends RawResolversConfig = RawResolversConfig,
TPluginConfig extends ParsedResolversConfig = ParsedResolversConfig
> extends BaseVisitor<TRawConfig, TPluginConfig> {
protected declare _parsedConfig: TPluginConfig;
protected _declarationBlockConfig: DeclarationBlockConfig = {};
protected _collectedResolvers: {
[key: string]: {
typename: string;
baseGeneratedTypename?: string;
};
} = {};
protected _parsedSchemaMeta: {
types: {
interface: Record<
string,
{
type: GraphQLInterfaceType;
implementingTypes: Record<string, GraphQLObjectType>;
}
>;
union: Record<
string,
{
type: GraphQLUnionType;
unionMembers: Record<string, GraphQLObjectType>;
}
>;
};
typesWithIsTypeOf: Record<string, true>;
} = {
types: {
interface: {},
union: {},
},
typesWithIsTypeOf: {},
};
protected _collectedDirectiveResolvers: { [key: string]: string } = {};
protected _variablesTransformer: OperationVariablesToObject;
protected _usedMappers: { [key: string]: boolean } = {};
protected _resolversTypes: ResolverTypes = {};
protected _resolversParentTypes: ResolverParentTypes = {};
protected _hasReferencedResolversUnionTypes = false;
protected _hasReferencedResolversInterfaceTypes = false;
protected _resolversUnionTypes: Record<string, string> = {};
protected _resolversInterfaceTypes: Record<string, string> = {};
protected _rootTypeNames = new Set<string>();
protected _globalDeclarations = new Set<string>();
protected _federation: ApolloFederation;
protected _hasScalars = false;
protected _fieldContextTypeMap: FieldContextTypeMap;
protected _directiveContextTypesMap: FieldContextTypeMap;
protected _checkedTypesWithNestedAbstractTypes: Record<string, { checkStatus: 'yes' | 'no' | 'checking' }> = {};
private _directiveResolverMappings: Record<string, string>;
private _shouldMapType: { [typeName: string]: boolean } = {};
constructor(
rawConfig: TRawConfig,
additionalConfig: TPluginConfig,
private _schema: GraphQLSchema,
defaultScalars: NormalizedScalarsMap = DEFAULT_SCALARS,
federationMeta: FederationMeta = {}
) {
super(rawConfig, {
immutableTypes: getConfigValue(rawConfig.immutableTypes, false),
optionalResolveType: getConfigValue(rawConfig.optionalResolveType, false),
enumPrefix: getConfigValue(rawConfig.enumPrefix, true),
enumSuffix: getConfigValue(rawConfig.enumSuffix, true),
federation: getConfigValue(rawConfig.federation, false),
resolverTypeWrapperSignature: getConfigValue(rawConfig.resolverTypeWrapperSignature, 'Promise<T> | T'),
enumValues: parseEnumValues({
schema: _schema,
mapOrStr: rawConfig.enumValues,
}),
addUnderscoreToArgsType: getConfigValue(rawConfig.addUnderscoreToArgsType, false),
addInterfaceFieldResolverTypes: getConfigValue(rawConfig.addInterfaceFieldResolverTypes, false),
contextType: parseMapper(rawConfig.contextType || 'any', 'ContextType'),
fieldContextTypes: getConfigValue(rawConfig.fieldContextTypes, []),
directiveContextTypes: getConfigValue(rawConfig.directiveContextTypes, []),
resolverTypeSuffix: getConfigValue(rawConfig.resolverTypeSuffix, 'Resolvers'),
allResolversTypeName: getConfigValue(rawConfig.allResolversTypeName, 'Resolvers'),
rootValueType: parseMapper(rawConfig.rootValueType || 'Record<PropertyKey, never>', 'RootValueType'),
namespacedImportName: getConfigValue(rawConfig.namespacedImportName, ''),
avoidOptionals: normalizeAvoidOptionals(rawConfig.avoidOptionals),
defaultMapper: rawConfig.defaultMapper
? parseMapper(rawConfig.defaultMapper || 'any', 'DefaultMapperType')
: null,
mappers: transformMappers(rawConfig.mappers || {}, rawConfig.mapperTypeSuffix),
scalars: buildScalarsFromConfig(_schema, rawConfig, defaultScalars),
internalResolversPrefix: getConfigValue(rawConfig.internalResolversPrefix, '__'),
generateInternalResolversIfNeeded: {},
resolversNonOptionalTypename: normalizeResolversNonOptionalTypename(
getConfigValue(rawConfig.resolversNonOptionalTypename, false)
),
avoidCheckingAbstractTypesRecursively: getConfigValue(rawConfig.avoidCheckingAbstractTypesRecursively, false),
...additionalConfig,
} as TPluginConfig);
autoBind(this);
this._federation = new ApolloFederation({
enabled: this.config.federation,
schema: this.schema,
meta: federationMeta,
});
this._rootTypeNames = getRootTypeNames(_schema);
this._variablesTransformer = new OperationVariablesToObject(
this.scalars,
this.convertName,
this.config.namespacedImportName
);
// 1. Parse schema meta at the start once,
// so we can use it in subsequent generate functions
this.parseSchemaMeta();
// 2. Generate types for resolvers
this._resolversTypes = this.createResolversFields({
applyWrapper: type => this.applyResolverTypeWrapper(type),
clearWrapper: type => this.clearResolverTypeWrapper(type),
getTypeToUse: name => this.getTypeToUse(name),
currentType: 'ResolversTypes',
onNotMappedObjectType: ({ initialType }) => initialType,
});
this._resolversParentTypes = this.createResolversFields({
applyWrapper: type => type,
clearWrapper: type => type,
getTypeToUse: name => this.getParentTypeToUse(name),
currentType: 'ResolversParentTypes',
shouldInclude: namedType => !isEnumType(namedType),
onNotMappedObjectType: ({ typeName, initialType }) => {
let result = initialType;
if (this._federation.getMeta()[typeName]?.referenceSelectionSetsString) {
result += ` | ${this.convertName('FederationReferenceTypes')}['${typeName}']`;
}
return result;
},
});
this._resolversUnionTypes = this.createResolversUnionTypes();
this._resolversInterfaceTypes = this.createResolversInterfaceTypes();
this._fieldContextTypeMap = this.createFieldContextTypeMap();
this._directiveContextTypesMap = this.createDirectivedContextType();
this._directiveResolverMappings = rawConfig.directiveResolverMappings ?? {};
}
public getResolverTypeWrapperSignature(): string {
return `export type ResolverTypeWrapper<T> = ${this.config.resolverTypeWrapperSignature};`;
}
protected shouldMapType(type: GraphQLNamedType, duringCheck: string[] = []): boolean {
if (type.name.startsWith('__') || this.config.scalars[type.name]) {
return false;
}
if (this.config.mappers[type.name]) {
return true;
}
if (isObjectType(type) || isInterfaceType(type)) {
const fields = type.getFields();
return Object.keys(fields)
.filter(fieldName => {
const field = fields[fieldName];
const fieldType = getBaseType(field.type);
return !duringCheck.includes(fieldType.name);
})
.some(fieldName => {
const field = fields[fieldName];
const fieldType = getBaseType(field.type);
if (this._shouldMapType[fieldType.name] !== undefined) {
return this._shouldMapType[fieldType.name];
}
if (this.config.mappers[type.name]) {
return true;
}
duringCheck.push(type.name);
const innerResult = this.shouldMapType(fieldType, duringCheck);
return innerResult;
});
}
return false;
}
public convertName(
node: ASTNode | string,
options?: BaseVisitorConvertOptions & ConvertOptions,
applyNamespacedImport = false
): string {
const sourceType = super.convertName(node, options);
return `${
applyNamespacedImport && this.config.namespacedImportName ? this.config.namespacedImportName + '.' : ''
}${sourceType}`;
}
// Kamil: this one is heeeeavvyyyy
protected createResolversFields({
applyWrapper,
clearWrapper,
getTypeToUse,
currentType,
shouldInclude,
onNotMappedObjectType,
}: {
applyWrapper: (str: string) => string;
clearWrapper: (str: string) => string;
getTypeToUse: (str: string) => string;
currentType: 'ResolversTypes' | 'ResolversParentTypes';
shouldInclude?: (type: GraphQLNamedType) => boolean;
onNotMappedObjectType: (params: { initialType: string; typeName: string }) => string;
}): ResolverTypes {
const allSchemaTypes = this._schema.getTypeMap();
const typeNames = this._federation.filterTypeNames(Object.keys(allSchemaTypes));
// avoid checking all types recursively if we have no `mappers` defined
if (Object.keys(this.config.mappers).length > 0) {
for (const typeName of typeNames) {
if (this._shouldMapType[typeName] === undefined) {
const schemaType = allSchemaTypes[typeName];
this._shouldMapType[typeName] = this.shouldMapType(schemaType);
}
}
}
return typeNames.reduce<ResolverTypes>((prev, typeName) => {
const schemaType = allSchemaTypes[typeName];
if (typeName.startsWith('__') || (shouldInclude && !shouldInclude(schemaType))) {
return prev;
}
const isRootType = this._rootTypeNames.has(typeName);
const isMapped = this.config.mappers[typeName];
const isScalar = this.config.scalars[typeName];
const hasDefaultMapper = !!this.config.defaultMapper?.type;
if (isRootType) {
prev[typeName] = applyWrapper(this.config.rootValueType.type);
return prev;
}
if (isMapped && this.config.mappers[typeName].type && !hasPlaceholder(this.config.mappers[typeName].type)) {
this.markMapperAsUsed(typeName);
prev[typeName] = applyWrapper(this.config.mappers[typeName].type);
} else if (isEnumType(schemaType) && this.config.enumValues[typeName]) {
const isExternalFile = !!this.config.enumValues[typeName].sourceFile;
prev[typeName] = isExternalFile
? this.convertName(this.config.enumValues[typeName].typeIdentifier, {
useTypesPrefix: false,
useTypesSuffix: false,
})
: this.config.enumValues[typeName].sourceIdentifier;
} else if (hasDefaultMapper && !hasPlaceholder(this.config.defaultMapper.type)) {
prev[typeName] = applyWrapper(this.config.defaultMapper.type);
} else if (isScalar) {
prev[typeName] = applyWrapper(this._getScalar(typeName));
} else if (isInterfaceType(schemaType)) {
this._hasReferencedResolversInterfaceTypes = true;
const type = this.convertName('ResolversInterfaceTypes');
const generic = this.convertName(currentType);
prev[typeName] = applyWrapper(`${type}<${generic}>['${typeName}']`);
return prev;
} else if (isUnionType(schemaType)) {