-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoutput.ts
More file actions
1202 lines (1187 loc) · 31.3 KB
/
output.ts
File metadata and controls
1202 lines (1187 loc) · 31.3 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 type {
GraphQLFieldExtensions,
GraphQLObjectTypeConfig,
GraphQLResolveInfo,
GraphQLUnionTypeConfig,
GraphQLArgumentConfig,
GraphQLInputFieldConfig,
GraphQLScalarTypeConfig,
FieldDefinitionNode,
} from "graphql";
import {
GArg,
GEnumType,
GEnumTypeConfig,
GEnumValueConfig,
GField,
GInputObjectType,
GInputObjectTypeConfig,
GInputType,
GInterfaceField,
GInterfaceType,
GInterfaceTypeConfig,
GList,
GNonNull,
GNullableInputType,
GNullableType,
GObjectType,
GOutputType,
GScalarType,
GType,
GUnionType,
InferValueFromOutputType,
InferValueFromArgs,
InferValueFromInputType,
} from "./types";
import {
GraphQLBoolean,
GraphQLID,
GraphQLInt,
GraphQLFloat,
GraphQLString,
} from "graphql";
import type { g } from "./g-for-doc-references";
type SomeTypeThatIsntARecordOfArgs = string;
type ImpliedResolver<
Args extends { [Key in keyof Args]: GArg<GInputType> },
Type extends GOutputType<Context>,
Context,
> =
| InferValueFromOutputType<Type>
| ((
args: InferValueFromArgs<Args>,
context: Context,
info: GraphQLResolveInfo
) => InferValueFromOutputType<Type>);
type Maybe<T> = T | null | undefined;
type FieldFuncArgs<
Source,
Args extends { [Key in keyof Args]: GArg<GInputType> },
Type extends GOutputType<Context>,
Context,
> = {
args?: Args;
type: Type;
description?: Maybe<string>;
deprecationReason?: Maybe<string>;
extensions?: Maybe<Readonly<GraphQLFieldExtensions<Source, Context>>>;
astNode?: Maybe<FieldDefinitionNode>;
};
/** @deprecated */
export type InterfaceToInterfaceFields<
Interface extends GInterfaceType<any, any, any>,
> = Interface extends GInterfaceType<any, infer Fields, any> ? Fields : never;
type InterfaceFieldsToOutputFields<
Source,
Context,
Fields extends { [key: string]: GInterfaceField<any, any, any> },
> = {
[Key in keyof Fields]: Fields[Key] extends GInterfaceField<
infer Args,
infer OutputType,
any
>
? GField<
Source,
Args,
OutputType,
Key extends keyof Source ? Source[Key] : unknown,
Context
>
: never;
};
/** @deprecated */
export type _InterfacesToOutputFields<
Source,
Context,
Interfaces extends readonly GInterfaceType<Source, any, Context>[],
> = InterfacesToOutputFields<Source, Context, Interfaces>;
export type { _InterfacesToOutputFields as InterfacesToOutputFields };
type InterfacesToOutputFields<
Source,
Context,
Interfaces extends readonly GInterfaceType<Source, any, any>[],
> = MergeTuple<
{
[Key in keyof Interfaces]: Interfaces[Key] extends GInterfaceType<
Source,
infer Fields,
any
>
? InterfaceFieldsToOutputFields<Source, Context, Fields>
: never;
},
{}
>;
export type InterfacesToInterfaceFields<
Interfaces extends readonly GInterfaceType<any, any, any>[],
> = MergeTuple<
{
[Key in keyof Interfaces]: Interfaces[Key] extends GInterfaceType<
any,
infer Fields,
any
>
? Fields
: never;
},
{}
>;
type MergeTuple<T, Merged> = T extends readonly [infer U, ...infer Rest]
? MergeTuple<Rest, Merged & U>
: Merged;
export type GWithContext<Context> = {
/**
* Creates a GraphQL object type.
*
* Note this is an **output** type, if you want an input object, use
* `g.inputObject`.
*
* When calling `g.object`, you must provide a type parameter that is the
* source of the object type. The source is what you receive as the first
* argument of resolvers on this type and what you must return from resolvers
* of fields that return this type.
*
* ```ts
* const Person = g.object<{ name: string }>()({
* name: "Person",
* fields: {
* name: g.field({ type: g.String }),
* },
* });
* // ==
* graphql`
* type Person {
* name: String
* }
* `;
* ```
*
* ## Writing resolvers
*
* To do anything other than just return a field from the source type, you
* need to provide a resolver.
*
* Note: TypeScript will force you to provide a resolve function if the field
* in the source type and the GraphQL field don't match
*
* ```ts
* const Person = g.object<{ name: string }>()({
* name: "Person",
* fields: {
* name: g.field({ type: g.String }),
* excitedName: g.field({
* type: g.String,
* resolve(source, args, context, info) {
* return `${source.name}!`;
* },
* }),
* },
* });
* ```
*
* ## Circularity
*
* GraphQL types will often contain references to themselves and to make
* TypeScript allow that, you need have an explicit type annotation of
* `g<typeof g.object<Source>>` along with making `fields` a function that
* returns the object.
*
* ```ts
* type PersonSource = { name: string; friends: PersonSource[] };
*
* const Person: g<typeof g.object<PersonSource>> =
* g.object<PersonSource>()({
* name: "Person",
* fields: () => ({
* name: g.field({ type: g.String }),
* friends: g.field({ type: g.list(Person) }),
* }),
* });
* ```
*/
object: <
Source,
>(youOnlyNeedToPassATypeParameterToThisFunctionYouPassTheActualRuntimeArgsOnTheResultOfThisFunction?: {
youOnlyNeedToPassATypeParameterToThisFunctionYouPassTheActualRuntimeArgsOnTheResultOfThisFunction: true;
}) => <
Fields extends {
[Key in keyof Fields]: GField<
Source,
any,
any,
Key extends keyof Source ? Source[Key] : unknown,
Context
>;
} & InterfaceFieldsToOutputFields<
Source,
Context,
InterfacesToInterfaceFields<Interfaces>
>,
const Interfaces extends readonly GInterfaceType<
Source,
any,
Context
>[] = [],
>(
config: {
fields: Fields | (() => Fields);
interfaces?: [...Interfaces];
} & Omit<GraphQLObjectTypeConfig<Source, Context>, "fields" | "interfaces">
) => GObjectType<Source, Context>;
/**
* Create a GraphQL union type.
*
* A union type represents an object that could be one of a list of types.
* Note it is similar to an {@link GInterfaceType interface type} except that a
* union doesn't imply having a common set of fields among the member types.
*
* ```ts
* const A = g.object<{ __typename: "A" }>()({
* name: "A",
* fields: {
* something: g.field({ type: g.String }),
* },
* });
* const B = g.object<{ __typename: "B" }>()({
* name: "B",
* fields: {
* differentThing: g.field({ type: g.String }),
* },
* });
* const AOrB = g.union({
* name: "AOrB",
* types: [A, B],
* });
* ```
*/
union: <Type extends GObjectType<any, Context>>(
config: Flatten<
Omit<
GraphQLUnionTypeConfig<
Type extends GObjectType<infer Source, Context> ? Source : never,
Context
>,
"types"
> & {
types: readonly Type[] | (() => readonly Type[]);
}
>
) => GUnionType<
Type extends GObjectType<infer Source, Context> ? Source : never,
Context
>;
/**
* Creates a GraphQL field.
*
* These will generally be passed directly to the `fields` object in a
* `g.object` call.
*
* ```ts
* const Something = g.object<{ thing: string }>()({
* name: "Something",
* fields: {
* thing: g.field({ type: g.String }),
* },
* });
* ```
*/
field: <
Source,
Type extends GOutputType<Context>,
Resolve,
Args extends { [Key in keyof Args]: GArg<GInputType> } = {},
>(
field: FieldFuncArgs<Source, Args, Type, Context> &
(Resolve extends {}
? {
resolve: ((
source: Source,
args: InferValueFromArgs<
SomeTypeThatIsntARecordOfArgs extends Args ? {} : Args
>,
context: Context,
info: GraphQLResolveInfo
) => InferValueFromOutputType<Type>) &
Resolve;
}
: {
resolve?: ((
source: Source,
args: InferValueFromArgs<
SomeTypeThatIsntARecordOfArgs extends Args ? {} : Args
>,
context: Context,
info: GraphQLResolveInfo
) => InferValueFromOutputType<Type>) &
Resolve;
})
) => GField<
Source,
Args,
Type,
Resolve extends {} ? unknown : ImpliedResolver<Args, Type, Context>,
Context
>;
/**
* A helper to declare fields while providing the source type a single time
* rather than in every resolver.
*
* ```ts
* const nodeFields = g.fields<{ id: string }>()({
* id: g.field({ type: g.ID }),
* relatedIds: g.field({
* type: g.list(g.ID),
* resolve(source) {
* return loadRelatedIds(source.id);
* },
* }),
* otherRelatedIds: g.field({
* type: g.list(g.ID),
* resolve(source) {
* return loadOtherRelatedIds(source.id);
* },
* }),
* });
*
* const Person = g.object<{
* id: string;
* name: string;
* }>()({
* name: "Person",
* fields: {
* ...nodeFields,
* name: g.field({ type: g.String }),
* },
* });
* ```
*/
fields: <
Source,
>(youOnlyNeedToPassATypeParameterToThisFunctionYouPassTheActualRuntimeArgsOnTheResultOfThisFunction?: {
youOnlyNeedToPassATypeParameterToThisFunctionYouPassTheActualRuntimeArgsOnTheResultOfThisFunction: true;
}) => <
Fields extends Record<
string,
GField<Source, any, GOutputType<Context>, any, Context>
> & {
[Key in keyof Source]?: GField<
Source,
any,
GOutputType<Context>,
Source[Key],
Context
>;
},
>(
fields: Fields
) => Fields;
/**
* Creates a GraphQL interface field.
*
* These will generally be passed directly to the `fields` object in a
* {@link g.interface} call. Interfaces fields are similar to
* {@link GField regular fields} except that they **don't define how the field
* is resolved**.
*
* ```ts
* const Entity = g.interface()({
* name: "Entity",
* fields: {
* name: g.interfaceField({ type: g.String }),
* },
* });
* ```
*
* Note that {@link GField regular fields} are assignable to
* {@link GInterfaceField interface fields} but the opposite is not true. This
* means that you can use a regular field in an
* {@link GInterfaceType interface type}.
*/
interfaceField: <
Args extends { [Key in keyof Args]: GArg<GInputType> },
Type extends GOutputType<Context>,
>(
field: GInterfaceField<Args, Type, Context>
) => GInterfaceField<Args, Type, Context>;
/**
* Creates a GraphQL interface type that can be implemented by other GraphQL
* object and interface types.
*
* ```ts
* const Entity = g.interface()({
* name: "Entity",
* fields: {
* name: g.interfaceField({ type: g.String }),
* },
* });
*
* type PersonSource = { __typename: "Person"; name: string };
*
* const Person = g.object<PersonSource>()({
* name: "Person",
* interfaces: [Entity],
* fields: {
* name: g.field({ type: g.String }),
* },
* });
*
* type OrganisationSource = {
* __typename: "Organisation";
* name: string;
* };
*
* const Organisation = g.object<OrganisationSource>()({
* name: "Organisation",
* interfaces: [Entity],
* fields: {
* name: g.field({ type: g.String }),
* },
* });
* ```
*
* ## Resolving Types
*
* When using GraphQL interface and union types, there needs to a way to
* determine which concrete object type has been returned from a resolver.
* With `graphql-js` and `@graphql-ts/schema`, this is done with `isTypeOf` on
* object types and `resolveType` on interface and union types. Note
* `@graphql-ts/schema` **does not aim to strictly type the implementation of
* `resolveType` and `isTypeOf`**. If you don't provide `resolveType` or
* `isTypeOf`, a `__typename` property on the source type will be used, if
* that fails, an error will be thrown at runtime.
*
* ## Fields vs Interface Fields
*
* You might have noticed that `g.interfaceField` was used instead of
* `g.field` for the fields on the interfaces. This is because **interfaces
* aren't defining implementation of fields** which means that fields on an
* interface don't need define resolvers.
*
* ## Sharing field implementations
*
* Even though interfaces don't contain field implementations, you may still
* want to share field implementations between interface implementations. You
* can use `g.fields` to do that. See `g.fields` for more information about
* why you should use `g.fields` instead of just defining an object the fields
* and spreading that.
*
* ```ts
* const nodeFields = g.fields<{ id: string }>({
* id: g.field({ type: g.ID }),
* });
*
* const Node = g.field({
* name: "Node",
* fields: nodeFields,
* });
*
* const Person = g.object<{
* __typename: "Person";
* id: string;
* name: string;
* }>()({
* name: "Person",
* interfaces: [Node],
* fields: {
* ...nodeFields,
* name: g.field({ type: g.String }),
* },
* });
* ```
*/
interface: <
Source,
>(youOnlyNeedToPassATypeParameterToThisFunctionYouPassTheActualRuntimeArgsOnTheResultOfThisFunction?: {
youOnlyNeedToPassATypeParameterToThisFunctionYouPassTheActualRuntimeArgsOnTheResultOfThisFunction: true;
}) => <
Fields extends {
[Key in keyof Fields]: GInterfaceField<
any,
GOutputType<Context>,
Context
>;
} & InterfacesToInterfaceFields<Interfaces>,
const Interfaces extends readonly GInterfaceType<
Source,
any,
Context
>[] = [],
>(
config: GInterfaceTypeConfig<Source, Fields, Interfaces, Context>
) => GInterfaceType<Source, Fields, Context>;
/**
* A shorthand to easily create {@link GEnumValueConfig enum values} to pass to
* {@link g.enum}.
*
* If you need to set a `description` or `deprecationReason` for an enum
* variant, you should pass values directly to `g.enum` without using
* `g.enumValues`.
*
* ```ts
* const MyEnum = g.enum({
* name: "MyEnum",
* values: g.enumValues(["a", "b"]),
* });
* ```
*
* ```ts
* const values = g.enumValues(["a", "b"]);
*
* assertDeepEqual(values, {
* a: { value: "a" },
* b: { value: "b" },
* });
* ```
*/
enumValues: <const Values extends readonly string[]>(
values: readonly [...Values]
) => {
[Key in Values[number]]: GEnumValueConfig<Key>;
};
/**
* Creates an {@link GEnumType enum type} with a number of
* {@link GEnumValueConfig enum values}.
*
* ```ts
* const MyEnum = g.enum({
* name: "MyEnum",
* values: g.enumValues(["a", "b"]),
* });
* // ==
* graphql`
* enum MyEnum {
* a
* b
* }
* `;
* ```
*
* ```ts
* const MyEnum = g.enum({
* name: "MyEnum",
* description: "My enum does things",
* values: {
* something: {
* description: "something something",
* value: "something",
* },
* thing: {
* description: "thing thing",
* deprecationReason: "something should be used instead of thing",
* value: "thing",
* },
* },
* });
* // ==
* graphql`
* """
* My enum does things
* """
* enum MyEnum {
* """
* something something
* """
* something
* """
* thing thing
* """
* thing @\deprecated(reason: "something should be used instead of thing")
* }
* `;)
* ```
*/
enum: <const Values extends Record<string, unknown>>(
config: GEnumTypeConfig<Values>
) => GEnumType<Values>;
/**
* Creates a {@link GArg GraphQL argument}.
*
* Args can can be used as arguments on output fields:
*
* ```ts
* g.field({
* type: g.String,
* args: {
* something: g.arg({ type: g.String }),
* },
* resolve(source, { something }) {
* return something || somethingElse;
* },
* });
* // ==
* graphql`(something: String): String`;
* ```
*
* Or as fields on input objects:
*
* ```ts
* const Something = g.inputObject({
* name: "Something",
* fields: {
* something: g.arg({ type: g.String }),
* },
* });
* // ==
* graphql`
* input Something {
* something: String
* }
* `;
* ```
*/
arg: <
Type extends GInputType,
DefaultValue extends InferValueFromInputType<Type> | undefined = undefined,
>(
arg: Flatten<
{
type: Type;
} & Omit<
GraphQLInputFieldConfig & GraphQLArgumentConfig,
"type" | "defaultValue"
>
> &
(undefined extends DefaultValue
? { defaultValue?: DefaultValue }
: { defaultValue: DefaultValue })
) => GArg<Type, DefaultValue extends undefined ? false : true>;
/**
* Creates an {@link GInputObjectType input object type}
*
* ```ts
* const Something = g.inputObject({
* name: "Something",
* fields: {
* something: g.arg({ type: g.String }),
* },
* });
* // ==
* graphql`
* input Something {
* something: String
* }
* `;
* ```
*
* ### Handling circular objects
*
* Circular input objects require explicitly specifying the fields on the
* object in the type because of TypeScript's limits with circularity.
*
* ```ts
* import { GInputObjectType } from "@graphql-ts/schema";
*
* type SomethingInputType = GInputObjectType<{
* something: g<typeof g.arg<SomethingInputType>>;
* }>;
* const Something: SomethingInputType = g.inputObject({
* name: "Something",
* fields: () => ({
* something: g.arg({ type: Something }),
* }),
* });
* ```
*
* You can specify all of your non-circular fields outside of the fields
* object and then use `typeof` to get the type to avoid writing the
* non-circular fields as types again.
*
* ```ts
* import { GInputObjectType } from "@graphql-ts/schema";
*
* const nonCircularFields = {
* thing: g.arg({ type: g.String }),
* };
* type SomethingInputType = GInputObjectType<
* typeof nonCircularFields & {
* something: g<typeof g.arg<SomethingInputType>>;
* }
* >;
* const Something: SomethingInputType = g.inputObject({
* name: "Something",
* fields: () => ({
* ...nonCircularFields,
* something: g.arg({ type: Something }),
* }),
* });
* ```
*/
inputObject: <
Fields extends {
[key: string]: IsOneOf extends true
? GArg<GNullableInputType, false>
: GArg<GInputType>;
},
IsOneOf extends boolean = false,
>(
config: GInputObjectTypeConfig<Fields, IsOneOf>
) => GInputObjectType<Fields, IsOneOf>;
/**
* Wraps any GraphQL type in a {@link GList list type}.
*
* ```ts
* const stringListType = g.list(g.String);
* // ==
* graphql`[String]`;
* ```
*
* When used as an input type, you will recieve an array of the inner type.
*
* ```ts
* g.field({
* type: g.String,
* args: { thing: g.arg({ type: g.list(g.String) }) },
* resolve(source, { thing }) {
* const theThing: undefined | null | Array<string | null> = thing;
* return "";
* },
* });
* ```
*
* When used as an output type, you can return an iterable of the inner type
* that also matches `typeof val === 'object'` so for example, you'll probably
* return an Array most of the time but you could also return a Set you
* couldn't return a string though, even though a string is an iterable, it
* doesn't match `typeof val === 'object'`.
*
* ```ts
* g.field({
* type: g.list(g.String),
* resolve() {
* return [""];
* },
* });
* ```
*
* ```ts
* g.field({
* type: g.list(g.String),
* resolve() {
* return new Set([""]);
* },
* });
* ```
*
* ```ts
* g.field({
* type: g.list(g.String),
* resolve() {
* // this will not be allowed
* return "some things";
* },
* });
* ```
*/
list: <Of extends GType<any>>(of: Of) => GList<Of>;
/**
* Wraps a {@link GNullableType nullable type} with a
* {@link GNonNull non-nullable type}.
*
* Types in GraphQL are always nullable by default so if you want to enforce
* that a type must always be there, you can use the non-null type.
*
* ```ts
* const nonNullableString = g.nonNull(g.String);
* // ==
* graphql`String!`;
* ```
*
* When using a non-null type as an input type, your resolver will never
* recieve null and consumers of your GraphQL API **must** provide a value for
* it unless you provide a default value.
*
* ```ts
* g.field({
* args: {
* someNonNullAndRequiredArg: g.arg({
* type: g.nonNull(g.String),
* }),
* someNonNullButOptionalArg: g.arg({
* type: g.nonNull(g.String),
* defaultValue: "some default",
* }),
* },
* type: g.String,
* resolve(source, args) {
* // both of these will always be a string
* args.someNonNullAndRequiredArg;
* args.someNonNullButOptionalArg;
*
* return "";
* },
* });
* // ==
* graphql`
* fieldName(
* someNonNullAndRequiredArg: String!
* someNonNullButOptionalArg: String! = "some default"
* ): String
* `;
* ```
*
* When using a non-null type as an output type, your resolver must never
* return null. If you do return null(which unless you do
* type-casting/ts-ignore/etc. `@graphql-ts/schema` will not let you do)
* graphql-js will return an error to consumers of your GraphQL API.
*
* Non-null types should be used very carefully on output types. If you have
* to do a fallible operation like a network request or etc. to get the value,
* it probably shouldn't be non-null. If you make a field non-null and doing
* the fallible operation fails, consumers of your GraphQL API will be unable
* to see any of the other fields on the object that the non-null field was
* on. For example, an id on some type is a good candidate for being non-null
* because if you have the item, you will already have the id so getting the
* id will never fail but fetching a related item from a database would be
* fallible so even if it will never be null in the success case, you should
* make it nullable.
*
* ```ts
* g.field({
* type: g.nonNull(g.String),
* resolve(source, args) {
* return "something";
* },
* });
* // ==
* graphql`
* fieldName: String!
* `;
* ```
*
* If you try to wrap another non-null type in a non-null type again, you will
* get a type error.
*
* ```ts
* // Argument of type 'NonNullType<ScalarType<string>>'
* // is not assignable to parameter of type 'NullableType'.
* g.nonNull(g.nonNull(g.String));
* ```
*/
nonNull: <Of extends GNullableType<any>>(of: Of) => GNonNull<Of>;
/**
* Creates a {@link GScalarType scalar type}.
*
* ```ts
* const BigInt = g.scalar({
* name: "BigInt",
* serialize(value) {
* if (typeof value !== "bigint")
* throw new GraphQLError(
* `unexpected value provided to BigInt scalar: ${value}`
* );
* return value.toString();
* },
* parseLiteral(value) {
* if (value.kind !== "StringValue")
* throw new GraphQLError("BigInt only accepts values as strings");
* return globalThis.BigInt(value.value);
* },
* parseValue(value) {
* if (typeof value === "bigint") return value;
* if (typeof value !== "string")
* throw new GraphQLError("BigInt only accepts values as strings");
* return globalThis.BigInt(value);
* },
* });
* // for fields on output types
* g.field({ type: someScalar });
*
* // for args on output fields or fields on input types
* g.arg({ type: someScalar });
* ```
*
* Note, while graphql-js allows you to express scalar types like the `ID`
* type which accepts integers and strings as both input values and return
* values from resolvers which are transformed into strings before calling
* resolvers and returning the query respectively, the type you use should be
* `string` for `ID` since that is what it is transformed into.
* `@graphql-ts/schema` doesn't currently express the coercion of scalars, you
* should instead convert values to the canonical form yourself before
* returning from resolvers.
*/
scalar: <Internal, External = Internal>(
config: GraphQLScalarTypeConfig<Internal, External>
) => GScalarType<Internal, External>;
ID: GScalarType<string>;
String: GScalarType<string>;
Float: GScalarType<number>;
Int: GScalarType<number>;
Boolean: GScalarType<boolean>;
};
/**
* The `gWithContext` function accepts a `Context` type parameter which binds
* the returned functions so they can be used to compose GraphQL types into a
* GraphQL schema.
*
* A simple schema with only a query type looks like this:
*
* ```ts
* import { gWithContext } from "@graphql-ts/schema";
* import { GraphQLSchema, graphql } from "graphql";
*
* type Context = {};
*
* const g = gWithContext<Context>();
* type g<T> = gWithContext.infer<T>;
*
* const Query = g.object()({
* name: "Query",
* fields: {
* hello: g.field({
* type: g.String,
* resolve() {
* return "Hello!";
* },
* }),
* },
* });
*
* const schema = new GraphQLSchema({
* query: Query,
* });
*
* graphql({
* source: `
* query {
* hello
* }
* `,
* schema,
* }).then((result) => {
* console.log(result);
* });
* ```
*
* You can use pass the `schema` to `ApolloServer` and other GraphQL servers.
*
* You can also create a more advanced schema with other object types, circular
* types, args, and mutations. See {@link GWithContext} for what the other
* functions on `g` do.
*
* ```ts
* import { gWithContext } from "@graphql-ts/schema";
* import { GraphQLSchema, graphql } from "graphql";
* import { deepEqual } from "node:assert";
*
* type Context = {
* todos: Map<string, TodoItem>;
* };
*
* const g = gWithContext<Context>();
* type g<T> = gWithContext.infer<T>;
*
* type TodoItem = {
* id: string;
* title: string;
* relatedTodos: string[];
* };
*
* const Todo: g<typeof g.object<TodoItem>> = g.object<TodoItem>()({
* name: "Todo",
* fields: () => ({
* id: g.field({ type: g.nonNull(g.ID) }),
* title: g.field({ type: g.nonNull(g.String) }),
* relatedTodos: g.field({
* type: g.list(Todo),
* resolve(source, _args, context) {