-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
base-types-visitor.ts
1038 lines (942 loc) · 33 KB
/
base-types-visitor.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 {
DirectiveDefinitionNode,
EnumTypeDefinitionNode,
EnumValueDefinitionNode,
FieldDefinitionNode,
GraphQLSchema,
InputObjectTypeDefinitionNode,
InputValueDefinitionNode,
InterfaceTypeDefinitionNode,
ListTypeNode,
NamedTypeNode,
NameNode,
NonNullTypeNode,
ObjectTypeDefinitionNode,
ScalarTypeDefinitionNode,
UnionTypeDefinitionNode,
StringValueNode,
isEnumType,
DirectiveNode,
Kind,
GraphQLEnumType,
} from 'graphql';
import { BaseVisitor, ParsedConfig, RawConfig } from './base-visitor.js';
import { DEFAULT_SCALARS } from './scalars.js';
import { normalizeDeclarationKind } from './declaration-kinds.js';
import {
EnumValuesMap,
NormalizedScalarsMap,
DeclarationKindConfig,
DeclarationKind,
ParsedEnumValuesMap,
DirectiveArgumentAndInputFieldMappings,
ParsedDirectiveArgumentAndInputFieldMappings,
} from './types.js';
import {
transformComment,
DeclarationBlock,
DeclarationBlockConfig,
indent,
wrapWithSingleQuotes,
getConfigValue,
buildScalarsFromConfig,
isOneOfInputObjectType,
} from './utils.js';
import { OperationVariablesToObject } from './variables-to-object.js';
import { parseEnumValues } from './enum-values.js';
import { transformDirectiveArgumentAndInputFieldMappings } from './mappers.js';
export interface ParsedTypesConfig extends ParsedConfig {
enumValues: ParsedEnumValuesMap;
declarationKind: DeclarationKindConfig;
addUnderscoreToArgsType: boolean;
onlyEnums: boolean;
onlyOperationTypes: boolean;
enumPrefix: boolean;
fieldWrapperValue: string;
wrapFieldDefinitions: boolean;
entireFieldWrapperValue: string;
wrapEntireDefinitions: boolean;
ignoreEnumValuesFromSchema: boolean;
directiveArgumentAndInputFieldMappings: ParsedDirectiveArgumentAndInputFieldMappings;
}
export interface RawTypesConfig extends RawConfig {
/**
* @description Adds `_` to generated `Args` types in order to avoid duplicate identifiers.
*
* @exampleMarkdown
* ## With Custom Values
*
* ```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 Overrides the default value of enum values declared in your GraphQL schema.
* You can also map the entire enum to an external type by providing a string that of `module#type`.
*
* @exampleMarkdown
* ## With Custom Values
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* enumValues: {
* MyEnum: {
* A: 'foo'
* }
* }
* },
* },
* },
* };
* export default config;
* ```
*
* ## With External Enum
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* enumValues: {
* MyEnum: './my-file#MyCustomEnum',
* }
* },
* },
* },
* };
* export default config;
* ```
*
* ## Import All Enums from a file
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* enumValues: {
* MyEnum: './my-file',
* }
* },
* },
* },
* };
* export default config;
* ```
*/
enumValues?: EnumValuesMap;
/**
* @description Overrides the default output for various GraphQL elements.
*
* @exampleMarkdown
* ## Override all declarations
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* declarationKind: 'interface'
* },
* },
* },
* };
* export default config;
* ```
*
* ## Override only specific declarations
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* declarationKind: {
* type: 'interface',
* input: 'interface'
* }
* },
* },
* },
* };
* export default config;
* ```
*/
declarationKind?: DeclarationKind | DeclarationKindConfig;
/**
* @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...
* config: {
* typesPrefix: 'I',
* enumPrefix: false
* },
* },
* },
* };
* export default config;
* ```
*/
enumPrefix?: boolean;
/**
* @description Allow you to add wrapper for field type, use T as the generic value. Make sure to set `wrapFieldDefinitions` to `true` in order to make this flag work.
* @default T
*
* @exampleMarkdown
* ## Allow Promise
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* wrapFieldDefinitions: true,
* fieldWrapperValue: 'T | Promise<T>',
* },
* },
* },
* };
* export default config;
* ```
*/
fieldWrapperValue?: string;
/**
* @description Set to `true` in order to wrap field definitions with `FieldWrapper`.
* This is useful to allow return types such as Promises and functions.
* @default false
*
* @exampleMarkdown
* ## Enable wrapping fields
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* wrapFieldDefinitions: true,
* },
* },
* },
* };
* export default config;
* ```
*/
wrapFieldDefinitions?: boolean;
/**
* @description This will cause the generator to emit types for enums only
* @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...
* config: {
* onlyEnums: true,
* },
* },
* },
* };
* export default config;
* ```
*/
onlyEnums?: boolean;
/**
* @description This will cause the generator to emit types for operations only (basically only enums and scalars)
* @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...
* config: {
* onlyOperationTypes: true,
* },
* },
* },
* };
* export default config;
* ```
*/
onlyOperationTypes?: boolean;
/**
* @description This will cause the generator to ignore enum values defined in GraphQLSchema
* @default false
*
* @exampleMarkdown
* ## Ignore enum values from schema
*
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* ignoreEnumValuesFromSchema: true,
* },
* },
* },
* };
* export default config;
* ```
*/
ignoreEnumValuesFromSchema?: boolean;
/**
* @name wrapEntireFieldDefinitions
* @type boolean
* @description Set to `true` in order to wrap field definitions with `EntireFieldWrapper`.
* This is useful to allow return types such as Promises and functions for fields.
* Differs from `wrapFieldDefinitions` in that this wraps the entire field definition if i.e. the field is an Array, while
* `wrapFieldDefinitions` will wrap every single value inside the array.
* @default true
*
* @example Enable wrapping entire fields
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* wrapEntireFieldDefinitions: false,
* },
* },
* },
* };
* export default config;
* ```
*/
wrapEntireFieldDefinitions?: boolean;
/**
* @name entireFieldWrapperValue
* @type string
* @description Allow to override the type value of `EntireFieldWrapper`. This wrapper applies outside of Array and Maybe
* unlike `fieldWrapperValue`, that will wrap the inner type.
* @default T | Promise<T> | (() => T | Promise<T>)
*
* @example Only allow values
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* entireFieldWrapperValue: 'T',
* },
* },
* },
* };
* export default config;
* ```
*/
entireFieldWrapperValue?: string;
/**
* @description Replaces a GraphQL scalar with a custom type based on the applied directive on an argument or input field.
*
* You can use both `module#type` and `module#namespace#type` syntax.
* Will NOT work with introspected schemas since directives are not exported.
* Only works with directives on ARGUMENT_DEFINITION or INPUT_FIELD_DEFINITION.
*
* **WARNING:** Using this option does only change the type definitions.
*
* For actually ensuring that a type is correct at runtime you will have to use schema transforms (e.g. with [@graphql-tools/utils mapSchema](https://graphql-tools.com/docs/schema-directives)) that apply those rules!
* Otherwise, you might end up with a runtime type mismatch which could cause unnoticed bugs or runtime errors.
*
* Please use this configuration option with care!
*
* @exampleMarkdown
* ## Custom Context Type\
* ```ts filename="codegen.ts"
* import type { CodegenConfig } from '@graphql-codegen/cli';
*
* const config: CodegenConfig = {
* // ...
* generates: {
* 'path/to/file': {
* // plugins...
* config: {
* directiveArgumentAndInputFieldMappings: {
* AsNumber: 'number',
* AsComplex: './my-models#Complex',
* }
* },
* },
* },
* };
* export default config;
* ```
*/
directiveArgumentAndInputFieldMappings?: DirectiveArgumentAndInputFieldMappings;
/**
* @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: {
* directiveArgumentAndInputFieldMappings: 'Model'
* },
* },
* },
* };
* export default config;
* ```
*/
directiveArgumentAndInputFieldMappingTypeSuffix?: string;
}
export class BaseTypesVisitor<
TRawConfig extends RawTypesConfig = RawTypesConfig,
TPluginConfig extends ParsedTypesConfig = ParsedTypesConfig
> extends BaseVisitor<TRawConfig, TPluginConfig> {
protected _argumentsTransformer: OperationVariablesToObject;
constructor(
protected _schema: GraphQLSchema,
rawConfig: TRawConfig,
additionalConfig: TPluginConfig,
defaultScalars: NormalizedScalarsMap = DEFAULT_SCALARS
) {
super(rawConfig, {
enumPrefix: getConfigValue(rawConfig.enumPrefix, true),
onlyEnums: getConfigValue(rawConfig.onlyEnums, false),
onlyOperationTypes: getConfigValue(rawConfig.onlyOperationTypes, false),
addUnderscoreToArgsType: getConfigValue(rawConfig.addUnderscoreToArgsType, false),
enumValues: parseEnumValues({
schema: _schema,
mapOrStr: rawConfig.enumValues,
ignoreEnumValuesFromSchema: rawConfig.ignoreEnumValuesFromSchema,
}),
declarationKind: normalizeDeclarationKind(rawConfig.declarationKind),
scalars: buildScalarsFromConfig(_schema, rawConfig, defaultScalars),
fieldWrapperValue: getConfigValue(rawConfig.fieldWrapperValue, 'T'),
wrapFieldDefinitions: getConfigValue(rawConfig.wrapFieldDefinitions, false),
entireFieldWrapperValue: getConfigValue(rawConfig.entireFieldWrapperValue, 'T'),
wrapEntireDefinitions: getConfigValue(rawConfig.wrapEntireFieldDefinitions, false),
ignoreEnumValuesFromSchema: getConfigValue(rawConfig.ignoreEnumValuesFromSchema, false),
directiveArgumentAndInputFieldMappings: transformDirectiveArgumentAndInputFieldMappings(
rawConfig.directiveArgumentAndInputFieldMappings ?? {},
rawConfig.directiveArgumentAndInputFieldMappingTypeSuffix
),
...additionalConfig,
});
// Note: Missing directive mappers but not a problem since always overriden by implementors
this._argumentsTransformer = new OperationVariablesToObject(this.scalars, this.convertName);
}
protected getExportPrefix(): string {
return 'export ';
}
public getFieldWrapperValue(): string {
if (this.config.fieldWrapperValue) {
return `${this.getExportPrefix()}type FieldWrapper<T> = ${this.config.fieldWrapperValue};`;
}
return '';
}
public getEntireFieldWrapperValue(): string {
if (this.config.entireFieldWrapperValue) {
return `${this.getExportPrefix()}type EntireFieldWrapper<T> = ${this.config.entireFieldWrapperValue};`;
}
return '';
}
public getScalarsImports(): string[] {
return Object.keys(this.config.scalars)
.map(enumName => {
const mappedValue = this.config.scalars[enumName];
if (mappedValue.isExternal) {
return this._buildTypeImport(mappedValue.import, mappedValue.source, mappedValue.default);
}
return null;
})
.filter(a => a);
}
public getDirectiveArgumentAndInputFieldMappingsImports(): string[] {
return Object.keys(this.config.directiveArgumentAndInputFieldMappings)
.map(directive => {
const mappedValue = this.config.directiveArgumentAndInputFieldMappings[directive];
if (mappedValue.isExternal) {
return this._buildTypeImport(mappedValue.import, mappedValue.source, mappedValue.default);
}
return null;
})
.filter(a => a);
}
public get scalarsDefinition(): string {
if (this.config.onlyEnums) return '';
const allScalars = Object.keys(this.config.scalars).map(scalarName => {
const scalarValue = this.config.scalars[scalarName].type;
const scalarType = this._schema.getType(scalarName);
const comment =
scalarType && scalarType.astNode && scalarType.description ? transformComment(scalarType.description, 1) : '';
const { scalar } = this._parsedConfig.declarationKind;
return comment + indent(`${scalarName}: ${scalarValue}${this.getPunctuation(scalar)}`);
});
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind(this._parsedConfig.declarationKind.scalar)
.withName('Scalars')
.withComment('All built-in and custom scalars, mapped to their actual values')
.withBlock(allScalars.join('\n')).string;
}
public get directiveArgumentAndInputFieldMappingsDefinition(): string {
const directiveEntries = Object.entries(this.config.directiveArgumentAndInputFieldMappings);
if (directiveEntries.length === 0) {
return '';
}
const allDirectives: Array<string> = [];
for (const [directiveName, parsedMapper] of directiveEntries) {
const directiveType = this._schema.getDirective(directiveName);
const comment =
directiveType?.astNode && directiveType.description ? transformComment(directiveType.description, 1) : '';
const { directive } = this._parsedConfig.declarationKind;
allDirectives.push(comment + indent(`${directiveName}: ${parsedMapper.type}${this.getPunctuation(directive)}`));
}
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind(this._parsedConfig.declarationKind.directive)
.withName('DirectiveArgumentAndInputFieldMappings')
.withComment('Type overrides using directives')
.withBlock(allDirectives.join('\n')).string;
}
setDeclarationBlockConfig(config: DeclarationBlockConfig): void {
this._declarationBlockConfig = config;
}
setArgumentsTransformer(argumentsTransfomer: OperationVariablesToObject): void {
this._argumentsTransformer = argumentsTransfomer;
}
NonNullType(node: NonNullTypeNode): string {
const asString = node.type as any as string;
return asString;
}
getInputObjectDeclarationBlock(node: InputObjectTypeDefinitionNode): DeclarationBlock {
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind(this._parsedConfig.declarationKind.input)
.withName(this.convertName(node))
.withComment(node.description as any as string)
.withBlock(node.fields.join('\n'));
}
getInputObjectOneOfDeclarationBlock(node: InputObjectTypeDefinitionNode): DeclarationBlock {
// As multiple fields always result in a union, we have
// to force a declaration kind of `type` in this case
const declarationKind = node.fields.length === 1 ? this._parsedConfig.declarationKind.input : 'type';
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind(declarationKind)
.withName(this.convertName(node))
.withComment(node.description as any as string)
.withContent(`\n` + node.fields.join('\n |'));
}
InputObjectTypeDefinition(node: InputObjectTypeDefinitionNode): string {
if (this.config.onlyEnums) return '';
// Why the heck is node.name a string and not { value: string } at runtime ?!
if (isOneOfInputObjectType(this._schema.getType(node.name as unknown as string))) {
return this.getInputObjectOneOfDeclarationBlock(node).string;
}
return this.getInputObjectDeclarationBlock(node).string;
}
InputValueDefinition(node: InputValueDefinitionNode): string {
if (this.config.onlyEnums) return '';
const comment = transformComment(node.description as any as string, 1);
const { input } = this._parsedConfig.declarationKind;
let type: string = node.type as any as string;
if (node.directives && this.config.directiveArgumentAndInputFieldMappings) {
type = this._getDirectiveOverrideType(node.directives) || type;
}
return comment + indent(`${node.name}: ${type}${this.getPunctuation(input)}`);
}
Name(node: NameNode): string {
return node.value;
}
FieldDefinition(node: FieldDefinitionNode): string {
if (this.config.onlyEnums) return '';
const typeString = node.type as any as string;
const { type } = this._parsedConfig.declarationKind;
const comment = this.getNodeComment(node);
return comment + indent(`${node.name}: ${typeString}${this.getPunctuation(type)}`);
}
UnionTypeDefinition(node: UnionTypeDefinitionNode, key: string | number | undefined, parent: any): string {
if (this.config.onlyOperationTypes || this.config.onlyEnums) return '';
const originalNode = parent[key] as UnionTypeDefinitionNode;
const possibleTypes = originalNode.types
.map(t => (this.scalars[t.name.value] ? this._getScalar(t.name.value) : this.convertName(t)))
.join(' | ');
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName(node))
.withComment(node.description as any as string)
.withContent(possibleTypes).string;
}
protected mergeInterfaces(interfaces: string[], hasOtherFields: boolean): string {
return interfaces.join(' & ') + (interfaces.length && hasOtherFields ? ' & ' : '');
}
appendInterfacesAndFieldsToBlock(block: DeclarationBlock, interfaces: string[], fields: string[]): void {
block.withContent(this.mergeInterfaces(interfaces, fields.length > 0));
block.withBlock(this.mergeAllFields(fields, interfaces.length > 0));
}
getObjectTypeDeclarationBlock(
node: ObjectTypeDefinitionNode,
originalNode: ObjectTypeDefinitionNode
): DeclarationBlock {
const optionalTypename = this.config.nonOptionalTypename ? '__typename' : '__typename?';
const { type, interface: interfacesType } = this._parsedConfig.declarationKind;
const allFields = [
...(this.config.addTypename
? [
indent(
`${this.config.immutableTypes ? 'readonly ' : ''}${optionalTypename}: '${node.name}'${this.getPunctuation(
type
)}`
),
]
: []),
...node.fields,
] as string[];
const interfacesNames = originalNode.interfaces ? originalNode.interfaces.map(i => this.convertName(i)) : [];
const declarationBlock = new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind(type)
.withName(this.convertName(node))
.withComment(node.description as any as string);
if (type === 'interface' || type === 'class') {
if (interfacesNames.length > 0) {
const keyword = interfacesType === 'interface' && type === 'class' ? 'implements' : 'extends';
declarationBlock.withContent(`${keyword} ` + interfacesNames.join(', ') + (allFields.length > 0 ? ' ' : ' {}'));
}
declarationBlock.withBlock(this.mergeAllFields(allFields, false));
} else {
this.appendInterfacesAndFieldsToBlock(declarationBlock, interfacesNames, allFields);
}
return declarationBlock;
}
protected mergeAllFields(allFields: string[], _hasInterfaces: boolean): string {
return allFields.join('\n');
}
ObjectTypeDefinition(node: ObjectTypeDefinitionNode, key: number | string, parent: any): string {
if (this.config.onlyOperationTypes || this.config.onlyEnums) return '';
const originalNode = parent[key] as ObjectTypeDefinitionNode;
return [this.getObjectTypeDeclarationBlock(node, originalNode).string, this.buildArgumentsBlock(originalNode)]
.filter(f => f)
.join('\n\n');
}
getInterfaceTypeDeclarationBlock(
node: InterfaceTypeDefinitionNode,
_originalNode: InterfaceTypeDefinitionNode
): DeclarationBlock {
const declarationBlock = new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind(this._parsedConfig.declarationKind.interface)
.withName(this.convertName(node))
.withComment(node.description as any as string);
return declarationBlock.withBlock(node.fields.join('\n'));
}
InterfaceTypeDefinition(node: InterfaceTypeDefinitionNode, key: number | string, parent: any): string {
if (this.config.onlyOperationTypes || this.config.onlyEnums) return '';
const originalNode = parent[key] as InterfaceTypeDefinitionNode;
return [this.getInterfaceTypeDeclarationBlock(node, originalNode).string, this.buildArgumentsBlock(originalNode)]
.filter(f => f)
.join('\n\n');
}
ScalarTypeDefinition(_node: ScalarTypeDefinitionNode): string {
// We empty this because we handle scalars in a different way, see constructor.
return '';
}
protected _buildTypeImport(identifier: string, source: string, asDefault = false): string {
const { useTypeImports } = this.config;
if (asDefault) {
if (useTypeImports) {
return `import type { default as ${identifier} } from '${source}';`;
}
return `import ${identifier} from '${source}';`;
}
return `import${useTypeImports ? ' type' : ''} { ${identifier} } from '${source}';`;
}
protected handleEnumValueMapper(
typeIdentifier: string,
importIdentifier: string | null,
sourceIdentifier: string | null,
sourceFile: string | null
): string[] {
if (importIdentifier !== sourceIdentifier) {
// use namespace import to dereference nested enum
// { enumValues: { MyEnum: './my-file#NS.NestedEnum' } }
return [
this._buildTypeImport(importIdentifier || sourceIdentifier, sourceFile),
`import ${typeIdentifier} = ${sourceIdentifier};`,
];
} else if (sourceIdentifier !== typeIdentifier) {
return [this._buildTypeImport(`${sourceIdentifier} as ${typeIdentifier}`, sourceFile)];
}
return [this._buildTypeImport(importIdentifier || sourceIdentifier, sourceFile)];
}
public getEnumsImports(): string[] {
return Object.keys(this.config.enumValues)
.flatMap(enumName => {
const mappedValue = this.config.enumValues[enumName];
if (mappedValue.sourceFile) {
if (mappedValue.isDefault) {
return [this._buildTypeImport(mappedValue.typeIdentifier, mappedValue.sourceFile, true)];
}
return this.handleEnumValueMapper(
mappedValue.typeIdentifier,
mappedValue.importIdentifier,
mappedValue.sourceIdentifier,
mappedValue.sourceFile
);
}
return [];
})
.filter(Boolean);
}
EnumTypeDefinition(node: EnumTypeDefinitionNode): string {
const enumName = node.name as any as string;
// In case of mapped external enum string
if (this.config.enumValues[enumName] && this.config.enumValues[enumName].sourceFile) {
return null;
}
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('enum')
.withName(this.convertName(node, { useTypesPrefix: this.config.enumPrefix }))
.withComment(node.description as any as string)
.withBlock(this.buildEnumValuesBlock(enumName, node.values)).string;
}
// We are using it in order to transform "description" field
StringValue(node: StringValueNode): string {
return node.value;
}
protected makeValidEnumIdentifier(identifier: string): string {
if (/^[0-9]/.exec(identifier)) {
return wrapWithSingleQuotes(identifier, true);
}
return identifier;
}
protected buildEnumValuesBlock(typeName: string, values: ReadonlyArray<EnumValueDefinitionNode>): string {
const schemaEnumType: GraphQLEnumType | undefined = this._schema
? (this._schema.getType(typeName) as GraphQLEnumType)
: undefined;
return values
.map(enumOption => {
const optionName = this.makeValidEnumIdentifier(
this.convertName(enumOption, {
useTypesPrefix: false,
transformUnderscore: true,
})
);
const comment = this.getNodeComment(enumOption);
const schemaEnumValue =
schemaEnumType && !this.config.ignoreEnumValuesFromSchema
? schemaEnumType.getValue(enumOption.name as any).value
: undefined;
let enumValue: string | number =
typeof schemaEnumValue !== 'undefined' ? schemaEnumValue : (enumOption.name as any);
if (
this.config.enumValues[typeName] &&
this.config.enumValues[typeName].mappedValues &&
typeof this.config.enumValues[typeName].mappedValues[enumValue] !== 'undefined'
) {
enumValue = this.config.enumValues[typeName].mappedValues[enumValue];
}
return (
comment +
indent(
`${optionName}${this._declarationBlockConfig.enumNameValueSeparator} ${wrapWithSingleQuotes(
enumValue,
typeof schemaEnumValue !== 'undefined'
)}`
)
);
})
.join(',\n');
}
DirectiveDefinition(_node: DirectiveDefinitionNode): string {
return '';
}
getArgumentsObjectDeclarationBlock(
node: InterfaceTypeDefinitionNode | ObjectTypeDefinitionNode,
name: string,
field: FieldDefinitionNode
): DeclarationBlock {
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind(this._parsedConfig.declarationKind.arguments)
.withName(this.convertName(name))
.withComment(node.description)
.withBlock(this._argumentsTransformer.transform<InputValueDefinitionNode>(field.arguments));
}
getArgumentsObjectTypeDefinition(
node: InterfaceTypeDefinitionNode | ObjectTypeDefinitionNode,
name: string,
field: FieldDefinitionNode
): string {
if (this.config.onlyEnums) return '';
return this.getArgumentsObjectDeclarationBlock(node, name, field).string;
}
protected buildArgumentsBlock(node: InterfaceTypeDefinitionNode | ObjectTypeDefinitionNode) {
const fieldsWithArguments = node.fields.filter(field => field.arguments && field.arguments.length > 0) || [];
return fieldsWithArguments
.map(field => {
const name =
node.name.value +
(this.config.addUnderscoreToArgsType ? '_' : '') +
this.convertName(field, {
useTypesPrefix: false,
useTypesSuffix: false,
}) +
'Args';
return this.getArgumentsObjectTypeDefinition(node, name, field);
})
.join('\n\n');
}
protected _getScalar(name: string): string {
return `Scalars['${name}']`;
}
protected _getDirectiveArgumentNadInputFieldMapping(name: string): string {
return `DirectiveArgumentAndInputFieldMappings['${name}']`;
}
protected _getDirectiveOverrideType(directives: ReadonlyArray<DirectiveNode>): string | null {
const type = directives
.map(directive => {
const directiveName = directive.name as any as string;
if (this.config.directiveArgumentAndInputFieldMappings[directiveName]) {
return this._getDirectiveArgumentNadInputFieldMapping(directiveName);
}
return null;
})
.reverse()
.find(a => !!a);
return type || null;
}
protected _getTypeForNode(node: NamedTypeNode): string {
const typeAsString = node.name as any as string;
if (this.scalars[typeAsString]) {
return this._getScalar(typeAsString);
}
if (this.config.enumValues[typeAsString]) {
return this.config.enumValues[typeAsString].typeIdentifier;
}
const schemaType = this._schema.getType(node.name as any);
if (schemaType && isEnumType(schemaType)) {
return this.convertName(node, { useTypesPrefix: this.config.enumPrefix });
}
return this.convertName(node);
}
NamedType(node: NamedTypeNode, key, parent, path, ancestors): string {
const currentVisitContext = this.getVisitorKindContextFromAncestors(ancestors);
const isVisitingInputType = currentVisitContext.includes(Kind.INPUT_OBJECT_TYPE_DEFINITION);
const typeToUse = this._getTypeForNode(node);
if (!isVisitingInputType && this.config.fieldWrapperValue && this.config.wrapFieldDefinitions) {
return `FieldWrapper<${typeToUse}>`;
}
return typeToUse;