-
-
Notifications
You must be signed in to change notification settings - Fork 76
/
InterfaceTypeComposer.js
1666 lines (1479 loc) · 53.3 KB
/
InterfaceTypeComposer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* @flow strict */
/* eslint-disable no-use-before-define */
import { GraphQLInterfaceType, GraphQLObjectType } from './graphql';
import { isObject, isString, isFunction } from './utils/is';
import { resolveMaybeThunk, inspect, mapEachKey } from './utils/misc';
import { ObjectTypeComposer } from './ObjectTypeComposer';
import type {
GraphQLFieldConfig,
GraphQLFieldConfigMap,
GraphQLOutputType,
GraphQLInputObjectType,
GraphQLInputType,
GraphQLResolveInfo,
GraphQLTypeResolver,
} from './graphql';
import { InputTypeComposer } from './InputTypeComposer';
import { UnionTypeComposer } from './UnionTypeComposer';
import { EnumTypeComposer } from './EnumTypeComposer';
import type { TypeAsString, TypeDefinitionString } from './TypeMapper';
import { SchemaComposer } from './SchemaComposer';
import type {
ObjectTypeComposerFieldConfigMap,
ObjectTypeComposerFieldConfig,
ObjectTypeComposerFieldConfigDefinition,
ObjectTypeComposerFieldConfigAsObjectDefinition,
ObjectTypeComposerFieldConfigMapDefinition,
ObjectTypeComposerArgumentConfigMapDefinition,
ObjectTypeComposerArgumentConfig,
ObjectTypeComposerArgumentConfigDefinition,
ObjectTypeComposerArgumentConfigMap,
} from './ObjectTypeComposer';
import { ListComposer } from './ListComposer';
import { NonNullComposer } from './NonNullComposer';
import { ThunkComposer } from './ThunkComposer';
import type {
Thunk,
Extensions,
MaybePromise,
DirectiveArgs,
ExtensionsDirective,
} from './utils/definitions';
import { toInputObjectType } from './utils/toInputType';
import { typeByPath, type TypeInPath } from './utils/typeByPath';
import {
getComposeTypeName,
getGraphQLType,
unwrapOutputTC,
unwrapInputTC,
isTypeNameString,
cloneTypeTo,
type NamedTypeComposer,
} from './utils/typeHelpers';
import {
defineFieldMap,
convertObjectFieldMapToConfig,
convertInterfaceArrayAsThunk,
} from './utils/configToDefine';
import { graphqlVersion } from './utils/graphqlVersion';
import type { ComposeNamedInputType, ComposeNamedOutputType } from './utils/typeHelpers';
import { printInterface, type SchemaPrinterOptions } from './utils/schemaPrinter';
import { getInterfaceTypeDefinitionNode } from './utils/definitionNode';
export type InterfaceTypeComposerDefinition<TSource, TContext> =
| TypeAsString
| TypeDefinitionString
| InterfaceTypeComposerAsObjectDefinition<TSource, TContext>
| GraphQLInterfaceType
| $ReadOnly<InterfaceTypeComposerThunked<any, TContext>>;
export type InterfaceTypeComposerAsObjectDefinition<TSource, TContext> = {
name: string,
fields?: ObjectTypeComposerFieldConfigMapDefinition<TSource, TContext>,
resolveType?: null | GraphQLTypeResolver<TSource, TContext>,
description?: null | string,
extensions?: Extensions,
};
export type InterfaceTypeComposerResolversMap<TContext> = Map<
ObjectTypeComposer<any, TContext> | GraphQLObjectType,
InterfaceTypeComposerResolverCheckFn<any, TContext>
>;
export type InterfaceTypeComposerResolverCheckFn<TSource, TContext> = (
value: TSource,
context: TContext,
info: GraphQLResolveInfo
) => MaybePromise<boolean | null | void>;
export type InterfaceTypeComposerThunked<TReturn, TContext> =
| InterfaceTypeComposer<TReturn, TContext>
| ThunkComposer<InterfaceTypeComposer<any, any>, GraphQLInterfaceType>;
export class InterfaceTypeComposer<TSource, TContext> {
schemaComposer: SchemaComposer<TContext>;
_gqType: GraphQLInterfaceType;
_gqcFields: ObjectTypeComposerFieldConfigMap<TSource, TContext>;
_gqcInputTypeComposer: void | InputTypeComposer<TContext>;
_gqcInterfaces: Array<InterfaceTypeComposerThunked<TSource, TContext>> = [];
_gqcTypeResolvers: void | InterfaceTypeComposerResolversMap<TContext>;
_gqcFallbackResolveType: ObjectTypeComposer<any, TContext> | GraphQLObjectType | null = null;
_gqcExtensions: void | Extensions;
// Also supported `GraphQLInterfaceType` but in such case FlowType force developers
// to explicitly write annotations in their code. But it's bad.
static create<TSrc, TCtx>(
typeDef: InterfaceTypeComposerDefinition<TSrc, TCtx>,
schemaComposer: SchemaComposer<TCtx>
): InterfaceTypeComposer<TSrc, TCtx> {
if (!(schemaComposer instanceof SchemaComposer)) {
throw new Error(
'You must provide SchemaComposer instance as a second argument for `InterfaceTypeComposer.create(typeDef, schemaComposer)`'
);
}
if (schemaComposer.hasInstance(typeDef, InterfaceTypeComposer)) {
return schemaComposer.getIFTC(typeDef);
}
const iftc = this.createTemp(typeDef, schemaComposer);
schemaComposer.add(iftc);
return iftc;
}
static createTemp<TSrc, TCtx>(
typeDef: InterfaceTypeComposerDefinition<TSrc, TCtx>,
schemaComposer?: SchemaComposer<TCtx>
): InterfaceTypeComposer<TSrc, TCtx> {
const sc = schemaComposer || new SchemaComposer();
let IFTC;
if (isString(typeDef)) {
const typeName: string = typeDef;
if (isTypeNameString(typeName)) {
IFTC = new InterfaceTypeComposer(
new GraphQLInterfaceType({
name: typeName,
fields: () => ({}),
}),
sc
);
} else {
IFTC = sc.typeMapper.convertSDLTypeDefinition(typeName);
if (!(IFTC instanceof InterfaceTypeComposer)) {
throw new Error(
'You should provide correct GraphQLInterfaceType type definition. ' +
'Eg. `interface MyType { id: ID!, name: String! }`'
);
}
}
} else if (typeDef instanceof GraphQLInterfaceType) {
IFTC = new InterfaceTypeComposer(typeDef, sc);
} else if (typeDef instanceof InterfaceTypeComposer) {
IFTC = typeDef;
} else if (
isObject(typeDef) &&
!(typeDef instanceof InterfaceTypeComposer) // hate Flow 😈
) {
const type = new GraphQLInterfaceType({
...(typeDef: any),
fields: () => ({}),
});
IFTC = new InterfaceTypeComposer(type, sc);
const fields = (typeDef: any).fields;
if (isFunction(fields)) {
// `convertOutputFieldMapToConfig` helps to solve hoisting problems
// rewrap fields `() => { f1: { type: A } }` -> `{ f1: { type: () => A } }`
IFTC.addFields(convertObjectFieldMapToConfig(fields, sc));
} else if (isObject(fields)) {
IFTC.addFields(fields);
}
const interfaces = (typeDef: any).interfaces;
if (Array.isArray(interfaces)) IFTC.setInterfaces(interfaces);
else if (isFunction(interfaces)) {
// rewrap interfaces `() => [i1, i2]` -> `[()=>i1, ()=>i2]`
// helps to solve hoisting problems
IFTC.setInterfaces(convertInterfaceArrayAsThunk(interfaces, sc));
}
IFTC._gqcExtensions = (typeDef: any).extensions || {};
} else {
throw new Error(
`You should provide GraphQLInterfaceTypeConfig or string with interface name or SDL definition. Provided:\n${inspect(
typeDef
)}`
);
}
return IFTC;
}
constructor(
graphqlType: GraphQLInterfaceType,
schemaComposer: SchemaComposer<TContext>
): InterfaceTypeComposer<TSource, TContext> {
if (!(schemaComposer instanceof SchemaComposer)) {
throw new Error(
'You must provide SchemaComposer instance as a second argument for `new InterfaceTypeComposer(GraphQLInterfaceType, SchemaComposer)`'
);
}
if (!(graphqlType instanceof GraphQLInterfaceType)) {
throw new Error('InterfaceTypeComposer accept only GraphQLInterfaceType in constructor');
}
this.schemaComposer = schemaComposer;
this._gqType = graphqlType;
// add itself to TypeStorage on create
// it avoids recursive type use errors
this.schemaComposer.set(graphqlType, this);
this.schemaComposer.set(graphqlType.name, this);
if (graphqlVersion >= 15) {
this._gqcFields = convertObjectFieldMapToConfig(this._gqType._fields, this.schemaComposer);
this._gqcInterfaces = convertInterfaceArrayAsThunk(
this._gqType._interfaces,
this.schemaComposer
);
} else if (graphqlVersion >= 14) {
this._gqcFields = convertObjectFieldMapToConfig(this._gqType._fields, this.schemaComposer);
} else {
// read
const fields: Thunk<GraphQLFieldConfigMap<any, TContext>> = (this._gqType: any)._typeConfig
.fields;
this._gqcFields = this.schemaComposer.typeMapper.convertOutputFieldConfigMap(
(resolveMaybeThunk(fields) || {}: any),
this.getTypeName()
);
}
if (graphqlType?.astNode?.directives) {
this.setExtension(
'directives',
this.schemaComposer.typeMapper.parseDirectives(graphqlType?.astNode?.directives)
);
}
// alive proper Flow type casting in autosuggestions for class with Generics
/* :: return this; */
}
// -----------------------------------------------
// Field methods
// -----------------------------------------------
getFields(): ObjectTypeComposerFieldConfigMap<TSource, TContext> {
return this._gqcFields;
}
getFieldNames(): string[] {
return Object.keys(this._gqcFields);
}
getField(fieldName: string): ObjectTypeComposerFieldConfig<TSource, TContext> {
// If FieldConfig is a Thunk then unwrap it on first read.
// In most cases FieldConfig is an object,
// but for solving hoisting problems it's quite good to wrap it in function.
if (isFunction(this._gqcFields[fieldName])) {
// $FlowFixMe
const unwrappedFieldConfig = this._gqcFields[fieldName]();
this.setField(fieldName, unwrappedFieldConfig);
}
const field = this._gqcFields[fieldName];
if (!field) {
throw new Error(
`Cannot get field '${fieldName}' from type '${this.getTypeName()}'. Field does not exist.`
);
}
return field;
}
hasField(fieldName: string): boolean {
return !!this._gqcFields[fieldName];
}
setFields(
fields: ObjectTypeComposerFieldConfigMapDefinition<TSource, TContext>
): InterfaceTypeComposer<TSource, TContext> {
this._gqcFields = {};
Object.keys(fields).forEach((name) => {
this.setField(name, fields[name]);
});
return this;
}
setField(
fieldName: string,
fieldConfig: ObjectTypeComposerFieldConfigDefinition<TSource, TContext>
): InterfaceTypeComposer<TSource, TContext> {
this._gqcFields[fieldName] = isFunction(fieldConfig)
? (fieldConfig: any)
: this.schemaComposer.typeMapper.convertOutputFieldConfig(
fieldConfig,
fieldName,
this.getTypeName()
);
return this;
}
/**
* Add new fields or replace existed in a GraphQL type
*/
addFields(
newFields: ObjectTypeComposerFieldConfigMapDefinition<TSource, TContext>
): InterfaceTypeComposer<TSource, TContext> {
Object.keys(newFields).forEach((name) => {
this.setField(name, newFields[name]);
});
return this;
}
/**
* Remove fields from type by name or array of names.
* You also may pass name in dot-notation, in such case will be removed nested field.
*
* @example
* removeField('field1'); // remove 1 field
* removeField(['field1', 'field2']); // remove 2 fields
* removeField('field1.subField1'); // remove 1 nested field
*/
removeField(fieldNameOrArray: string | string[]): InterfaceTypeComposer<TSource, TContext> {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
fieldNames.forEach((fieldName) => {
const names = fieldName.split('.');
const name = names.shift();
if (names.length === 0) {
// single field
delete this._gqcFields[name];
} else {
// nested field
// eslint-disable-next-line no-lonely-if
if (this.hasField(name)) {
const subTC = this.getFieldTC(name);
if (subTC instanceof ObjectTypeComposer || subTC instanceof EnumTypeComposer) {
subTC.removeField(names.join('.'));
}
}
}
});
return this;
}
removeOtherFields(fieldNameOrArray: string | string[]): InterfaceTypeComposer<TSource, TContext> {
const keepFieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
Object.keys(this._gqcFields).forEach((fieldName) => {
if (keepFieldNames.indexOf(fieldName) === -1) {
delete this._gqcFields[fieldName];
}
});
return this;
}
reorderFields(names: string[]): InterfaceTypeComposer<TSource, TContext> {
const orderedFields = {};
const fields = this._gqcFields;
names.forEach((name) => {
if (fields[name]) {
orderedFields[name] = fields[name];
delete fields[name];
}
});
this._gqcFields = { ...orderedFields, ...fields };
return this;
}
extendField(
fieldName: string,
partialFieldConfig: $Shape<ObjectTypeComposerFieldConfigAsObjectDefinition<TSource, TContext>>
): InterfaceTypeComposer<TSource, TContext> {
let prevFieldConfig;
try {
prevFieldConfig = this.getField(fieldName);
} catch (e) {
throw new Error(
`Cannot extend field '${fieldName}' from type '${this.getTypeName()}'. Field does not exist.`
);
}
this.setField(fieldName, {
...prevFieldConfig,
...(partialFieldConfig: any),
extensions: {
...(prevFieldConfig.extensions || {}),
...((partialFieldConfig.extensions: any) || {}),
},
});
return this;
}
getFieldConfig(fieldName: string): GraphQLFieldConfig<TSource, TContext> {
const { type, args, ...rest } = this.getField(fieldName);
return ({
type: type.getType(),
args:
args &&
mapEachKey(args, (ac) => ({
...ac,
type: ac.type.getType(),
})),
...(rest: any),
}: any);
}
getFieldType(fieldName: string): GraphQLOutputType {
return this.getField(fieldName).type.getType();
}
getFieldTypeName(fieldName: string): string {
return this.getField(fieldName).type.getTypeName();
}
/**
* Automatically unwrap from List, NonNull, ThunkComposer
* It's important! Cause greatly helps to modify fields types in a real code
* without manual unwrap writing.
*
* If you need to work with wrappers, you may use the following code:
* - `TC.getField().type` // returns real wrapped TypeComposer
* - `TC.isFieldNonNull()` // checks is field NonNull or not
* - `TC.makeFieldNonNull()` // for wrapping in NonNullComposer
* - `TC.makeFieldNullable()` // for unwrapping from NonNullComposer
* - `TC.isFieldPlural()` // checks is field wrapped in ListComposer or not
* - `TC.makeFieldPlural()` // for wrapping in ListComposer
* - `TC.makeFieldNonPlural()` // for unwrapping from ListComposer
*/
getFieldTC(fieldName: string): ComposeNamedOutputType<TContext> {
const anyTC = this.getField(fieldName).type;
return unwrapOutputTC(anyTC);
}
/**
* Alias for `getFieldTC()` but returns statically checked ObjectTypeComposer.
* If field have other type then error will be thrown.
*/
getFieldOTC(fieldName: string): ObjectTypeComposer<TSource, TContext> {
const tc = this.getFieldTC(fieldName);
if (!(tc instanceof ObjectTypeComposer)) {
throw new Error(
`${this.getTypeName()}.getFieldOTC('${fieldName}') must be ObjectTypeComposer, but received ${
tc.constructor.name
}. Maybe you need to use 'getFieldTC()' method which returns any type composer?`
);
}
return tc;
}
isFieldNonNull(fieldName: string): boolean {
return this.getField(fieldName).type instanceof NonNullComposer;
}
makeFieldNonNull(fieldNameOrArray: string | string[]): InterfaceTypeComposer<TSource, TContext> {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
fieldNames.forEach((fieldName) => {
const fc = this._gqcFields[fieldName];
if (fc && !(fc.type instanceof NonNullComposer)) {
fc.type = new NonNullComposer(fc.type);
}
});
return this;
}
makeFieldNullable(fieldNameOrArray: string | string[]): InterfaceTypeComposer<TSource, TContext> {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
fieldNames.forEach((fieldName) => {
const fc = this._gqcFields[fieldName];
if (fc && fc.type instanceof NonNullComposer) {
fc.type = fc.type.ofType;
}
});
return this;
}
isFieldPlural(fieldName: string): boolean {
const type = this.getField(fieldName).type;
return (
type instanceof ListComposer ||
(type instanceof NonNullComposer && type.ofType instanceof ListComposer)
);
}
makeFieldPlural(fieldNameOrArray: string | string[]): InterfaceTypeComposer<TSource, TContext> {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
fieldNames.forEach((fieldName) => {
const fc = this._gqcFields[fieldName];
if (fc && !(fc.type instanceof ListComposer)) {
fc.type = new ListComposer(fc.type);
}
});
return this;
}
makeFieldNonPlural(
fieldNameOrArray: string | string[]
): InterfaceTypeComposer<TSource, TContext> {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
fieldNames.forEach((fieldName) => {
const fc = this._gqcFields[fieldName];
if (fc) {
if (fc.type instanceof ListComposer) {
fc.type = fc.type.ofType;
} else if (fc.type instanceof NonNullComposer && fc.type.ofType instanceof ListComposer) {
fc.type =
fc.type.ofType.ofType instanceof NonNullComposer
? fc.type.ofType.ofType
: new NonNullComposer(fc.type.ofType.ofType);
}
}
});
return this;
}
deprecateFields(
fields: { [fieldName: string]: string } | string[] | string
): InterfaceTypeComposer<TSource, TContext> {
const existedFieldNames = this.getFieldNames();
if (typeof fields === 'string') {
if (existedFieldNames.indexOf(fields) === -1) {
throw new Error(
`Cannot deprecate non-existent field '${fields}' from interface type '${this.getTypeName()}'`
);
}
this.extendField(fields, { deprecationReason: 'deprecated' });
} else if (Array.isArray(fields)) {
fields.forEach((field) => {
if (existedFieldNames.indexOf(field) === -1) {
throw new Error(
`Cannot deprecate non-existent field '${field}' from interface type '${this.getTypeName()}'`
);
}
this.extendField(field, { deprecationReason: 'deprecated' });
});
} else {
const fieldMap: Object = (fields: any);
Object.keys(fieldMap).forEach((field) => {
if (existedFieldNames.indexOf(field) === -1) {
throw new Error(
`Cannot deprecate non-existent field '${field}' from interface type '${this.getTypeName()}'`
);
}
const deprecationReason: string = fieldMap[field];
this.extendField(field, { deprecationReason });
});
}
return this;
}
getFieldArgs<TArgs = any>(fieldName: string): ObjectTypeComposerArgumentConfigMap<TArgs> {
try {
const fc = this.getField(fieldName);
return fc.args || {};
} catch (e) {
throw new Error(
`Cannot get field args. Field '${fieldName}' from type '${this.getTypeName()}' does not exist.`
);
}
}
getFieldArgNames(fieldName: string): string[] {
return Object.keys(this.getFieldArgs(fieldName));
}
hasFieldArg(fieldName: string, argName: string): boolean {
try {
const fieldArgs = this.getFieldArgs(fieldName);
return !!fieldArgs[argName];
} catch (e) {
return false;
}
}
getFieldArg(fieldName: string, argName: string): ObjectTypeComposerArgumentConfig {
const fieldArgs = this.getFieldArgs(fieldName);
const arg = fieldArgs[argName];
if (!arg) {
throw new Error(
`Cannot get '${this.getTypeName()}.${fieldName}@${argName}'. Argument does not exist.`
);
}
return arg;
}
getFieldArgType(fieldName: string, argName: string): GraphQLInputType {
const ac = this.getFieldArg(fieldName, argName);
return ac.type.getType();
}
getFieldArgTypeName(fieldName: string, argName: string): string {
const ac = this.getFieldArg(fieldName, argName);
return ac.type.getTypeName();
}
/**
* Automatically unwrap from List, NonNull, ThunkComposer
* It's important! Cause greatly helps to modify args types in a real code
* without manual unwrap writing.
*
* If you need to work with wrappers, you may use the following code:
* `isFieldArgPlural()` – checks is arg wrapped in ListComposer or not
* `makeFieldArgPlural()` – for arg wrapping in ListComposer
* `makeFieldArgNonPlural()` – for arg unwrapping from ListComposer
* `isFieldArgNonNull()` – checks is arg wrapped in NonNullComposer or not
* `makeFieldArgNonNull()` – for arg wrapping in NonNullComposer
* `makeFieldArgNullable()` – for arg unwrapping from NonNullComposer
*/
getFieldArgTC(fieldName: string, argName: string): ComposeNamedInputType<TContext> {
const anyTC = this.getFieldArg(fieldName, argName).type;
return unwrapInputTC(anyTC);
}
/**
* Alias for `getFieldArgTC()` but returns statically checked InputTypeComposer.
* If field have other type then error will be thrown.
*/
getFieldArgITC(fieldName: string, argName: string): InputTypeComposer<TContext> {
const tc = this.getFieldArgTC(fieldName, argName);
if (!(tc instanceof InputTypeComposer)) {
throw new Error(
`${this.getTypeName()}.getFieldArgITC('${fieldName}', '${argName}') must be InputTypeComposer, but received ${
tc.constructor.name
}. Maybe you need to use 'getFieldArgTC()' method which returns any type composer?`
);
}
return tc;
}
setFieldArgs(
fieldName: string,
args: ObjectTypeComposerArgumentConfigMapDefinition<any>
): InterfaceTypeComposer<TSource, TContext> {
const fc = this.getField(fieldName);
fc.args = this.schemaComposer.typeMapper.convertArgConfigMap(
args,
fieldName,
this.getTypeName()
);
return this;
}
addFieldArgs(
fieldName: string,
newArgs: ObjectTypeComposerArgumentConfigMapDefinition<any>
): InterfaceTypeComposer<TSource, TContext> {
const fc = this.getField(fieldName);
fc.args = {
...fc.args,
...this.schemaComposer.typeMapper.convertArgConfigMap(newArgs, fieldName, this.getTypeName()),
};
return this;
}
setFieldArg(
fieldName: string,
argName: string,
argConfig: ObjectTypeComposerArgumentConfigDefinition
): InterfaceTypeComposer<TSource, TContext> {
const fc = this.getField(fieldName);
fc.args = fc.args || {};
(fc.args: any)[argName] = this.schemaComposer.typeMapper.convertArgConfig(
argConfig,
argName,
fieldName,
this.getTypeName()
);
return this;
}
isFieldArgPlural(fieldName: string, argName: string): boolean {
const type = this.getFieldArg(fieldName, argName).type;
return (
type instanceof ListComposer ||
(type instanceof NonNullComposer && type.ofType instanceof ListComposer)
);
}
makeFieldArgPlural(
fieldName: string,
argNameOrArray: string | string[]
): InterfaceTypeComposer<TSource, TContext> {
const args = this.getField(fieldName).args;
if (!args) return this;
const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray];
argNames.forEach((argName) => {
const ac = args[argName];
if (ac && !(ac.type instanceof ListComposer)) {
ac.type = new ListComposer(ac.type);
}
});
return this;
}
makeFieldArgNonPlural(
fieldName: string,
argNameOrArray: string | string[]
): InterfaceTypeComposer<TSource, TContext> {
const args = this.getField(fieldName).args;
if (!args) return this;
const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray];
argNames.forEach((argName) => {
const ac = args[argName];
if (ac) {
if (ac.type instanceof ListComposer) {
ac.type = ac.type.ofType;
} else if (ac.type instanceof NonNullComposer && ac.type.ofType instanceof ListComposer) {
ac.type =
ac.type.ofType.ofType instanceof NonNullComposer
? ac.type.ofType.ofType
: new NonNullComposer(ac.type.ofType.ofType);
}
}
});
return this;
}
isFieldArgNonNull(fieldName: string, argName: string): boolean {
const type = this.getFieldArg(fieldName, argName).type;
return type instanceof NonNullComposer;
}
makeFieldArgNonNull(
fieldName: string,
argNameOrArray: string | string[]
): InterfaceTypeComposer<TSource, TContext> {
const args = this.getField(fieldName).args;
if (!args) return this;
const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray];
argNames.forEach((argName) => {
const ac = args[argName];
if (ac && !(ac.type instanceof NonNullComposer)) {
ac.type = new NonNullComposer(ac.type);
}
});
return this;
}
makeFieldArgNullable(
fieldName: string,
argNameOrArray: string | string[]
): InterfaceTypeComposer<TSource, TContext> {
const args = this.getField(fieldName).args;
if (!args) return this;
const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray];
argNames.forEach((argName) => {
const ac = args[argName];
if (ac && ac.type instanceof NonNullComposer) {
ac.type = ac.type.ofType;
}
});
return this;
}
// -----------------------------------------------
// Type methods
// -----------------------------------------------
getType(): GraphQLInterfaceType {
this._gqType.astNode = getInterfaceTypeDefinitionNode(this);
if (graphqlVersion >= 15) {
this._gqType._fields = () =>
defineFieldMap(
this._gqType,
mapEachKey(this._gqcFields, (fc, name) => this.getFieldConfig(name)),
this._gqType.astNode
);
this._gqType._interfaces = () => this.getInterfacesTypes();
} else if (graphqlVersion >= 14) {
this._gqType._fields = () =>
defineFieldMap(
this._gqType,
mapEachKey(this._gqcFields, (fc, name) => this.getFieldConfig(name)),
this._gqType.astNode
);
} else {
(this._gqType: any)._typeConfig.fields = () => {
return mapEachKey(this._gqcFields, (fc, name) => this.getFieldConfig(name));
};
this._gqType._fields = {}; // clear builded fields in type
}
return this._gqType;
}
getTypePlural(): ListComposer<InterfaceTypeComposer<TSource, TContext>> {
return new ListComposer(this);
}
getTypeNonNull(): NonNullComposer<InterfaceTypeComposer<TSource, TContext>> {
return new NonNullComposer(this);
}
/**
* Get Type wrapped in List modifier
*
* @example
* const UserTC = schemaComposer.createInterfaceTC(`interface UserIface { name: String }`);
* schemaComposer.Query.addFields({
* users1: { type: UserTC.List }, // in SDL: users1: [UserIface]
* users2: { type: UserTC.NonNull.List }, // in SDL: users2: [UserIface!]
* users3: { type: UserTC.NonNull.List.NonNull }, // in SDL: users2: [UserIface!]!
* })
*/
get List(): ListComposer<InterfaceTypeComposer<TSource, TContext>> {
return new ListComposer(this);
}
/**
* Get Type wrapped in NonNull modifier
*
* @example
* const UserTC = schemaComposer.createInterfaceTC(`interface UserIface { name: String }`);
* schemaComposer.Query.addFields({
* users1: { type: UserTC.List }, // in SDL: users1: [UserIface]
* users2: { type: UserTC.NonNull.List }, // in SDL: users2: [UserIface!]!
* users3: { type: UserTC.NonNull.List.NonNull }, // in SDL: users2: [UserIface!]!
* })
*/
get NonNull(): NonNullComposer<InterfaceTypeComposer<TSource, TContext>> {
return new NonNullComposer(this);
}
getTypeName(): string {
return this._gqType.name;
}
setTypeName(name: string): InterfaceTypeComposer<TSource, TContext> {
this._gqType.name = name;
this.schemaComposer.add(this);
return this;
}
getDescription(): string {
return this._gqType.description || '';
}
setDescription(description: string): InterfaceTypeComposer<TSource, TContext> {
this._gqType.description = description;
return this;
}
/**
* You may clone this type with a new provided name as string.
* Or you may provide a new TypeComposer which will get all cloned
* settings from this type.
*/
clone(
newTypeNameOrTC: string | InterfaceTypeComposer<any, any>
): InterfaceTypeComposer<TSource, TContext> {
if (!newTypeNameOrTC) {
throw new Error('You should provide newTypeName:string for InterfaceTypeComposer.clone()');
}
const cloned =
newTypeNameOrTC instanceof InterfaceTypeComposer
? newTypeNameOrTC
: InterfaceTypeComposer.create(newTypeNameOrTC, this.schemaComposer);
cloned._gqcFields = mapEachKey(this._gqcFields, (fieldConfig) => ({
...fieldConfig,
args: mapEachKey(fieldConfig.args, (argConfig) => ({
...argConfig,
extensions: { ...argConfig.extensions },
})),
extensions: { ...fieldConfig.extensions },
}));
cloned._gqcInterfaces = [...this._gqcInterfaces];
cloned._gqcTypeResolvers = new Map(this._gqcTypeResolvers);
cloned._gqcFallbackResolveType = this._gqcFallbackResolveType;
cloned._gqcExtensions = { ...this._gqcExtensions };
cloned.setDescription(this.getDescription());
return cloned;
}
/**
* Clone this type to another SchemaComposer.
* Also will be cloned all sub-types.
*/
cloneTo(
anotherSchemaComposer: SchemaComposer<any>,
cloneMap?: Map<any, any> = new Map()
): InterfaceTypeComposer<any, any> {
if (!anotherSchemaComposer) {
throw new Error('You should provide SchemaComposer for InterfaceTypeComposer.cloneTo()');
}
if (cloneMap.has(this)) return (cloneMap.get(this): any);
const cloned = InterfaceTypeComposer.create(this.getTypeName(), anotherSchemaComposer);
cloneMap.set(this, cloned);
cloned._gqcFields = mapEachKey(this._gqcFields, (fieldConfig) => ({
...fieldConfig,
type: cloneTypeTo(fieldConfig.type, anotherSchemaComposer, cloneMap),
args: mapEachKey(fieldConfig.args, (argConfig) => ({
...argConfig,
type: cloneTypeTo(argConfig.type, anotherSchemaComposer, cloneMap),
extensions: { ...argConfig.extensions },
})),
extensions: { ...fieldConfig.extensions },
}));
cloned._gqcInterfaces = (this._gqcInterfaces.map((i) =>
i.cloneTo(anotherSchemaComposer, cloneMap)
): any);
cloned._gqcExtensions = { ...this._gqcExtensions };
cloned.setDescription(this.getDescription());
// clone this._gqcTypeResolvers
const typeResolversMap = this.getTypeResolvers();
if (typeResolversMap.size > 0) {
const clonedTypeResolvers: InterfaceTypeComposerResolversMap<any> = new Map();
typeResolversMap.forEach((fn, tc) => {
const clonedTC: ObjectTypeComposer<any, any> | GraphQLObjectType = (cloneTypeTo(
tc,
anotherSchemaComposer,
cloneMap
): any);
clonedTypeResolvers.set(clonedTC, fn);
});
cloned.setTypeResolvers(clonedTypeResolvers);
}
if (this._gqcFallbackResolveType) {
cloned._gqcFallbackResolveType = (cloneTypeTo(
this._gqcFallbackResolveType,
anotherSchemaComposer,
cloneMap
): any);
}
return cloned;
}
merge(
type:
| GraphQLInterfaceType
| GraphQLObjectType
| InterfaceTypeComposer<any, any>
| ObjectTypeComposer<any, any>
): InterfaceTypeComposer<TSource, TContext> {
let tc;
if (type instanceof ObjectTypeComposer || type instanceof InterfaceTypeComposer) {
tc = type;
} else if (type instanceof GraphQLObjectType) {
tc = ObjectTypeComposer.createTemp(type, this.schemaComposer);
} else if (type instanceof GraphQLInterfaceType) {
tc = InterfaceTypeComposer.createTemp(type, this.schemaComposer);
} else {
throw new Error(
`Cannot merge ${inspect(
type
)} with InterfaceType(${this.getTypeName()}). Provided type should be GraphQLInterfaceType, GraphQLObjectType, InterfaceTypeComposer or ObjectTypeComposer.`
);
}
// deep clone all fields with args
const fields = ({ ...tc.getFields() }: any);
Object.keys(fields).forEach((fieldName) => {
fields[fieldName] = {
...fields[fieldName],
args: {
...fields[fieldName].args,
},
// set type as SDL string, it automatically will be remapped to the correct type instance in the current schema
type: tc.getFieldTypeName(fieldName),
};
tc.getFieldArgNames(fieldName).forEach((argName) => {
fields[fieldName].args[argName] = {
...fields[fieldName].args[argName],
// set type as SDL string, it automatically will be remapped to the correct type instance in the current schema
type: tc.getFieldArgTypeName(fieldName, argName),
};
});
});
this.addFields(fields);
// set interfaces as SDL string, it automatically will be remapped to the correct type instance in the current schema
this.addInterfaces(tc.getInterfaces().map((i) => i.getTypeName()));
// Feel free to add other properties for merging two TypeComposers.
// For simplicity it just merge fields and interfaces.
return this;
}
// -----------------------------------------------
// InputType methods
// -----------------------------------------------
getInputType(): GraphQLInputObjectType {
return this.getInputTypeComposer().getType();
}
hasInputTypeComposer(): boolean {
return !!this._gqcInputTypeComposer;
}
setInputTypeComposer(itc: InputTypeComposer<TContext>): InterfaceTypeComposer<TSource, TContext> {
this._gqcInputTypeComposer = itc;