-
Notifications
You must be signed in to change notification settings - Fork 841
/
definition.go
1354 lines (1200 loc) · 33.1 KB
/
definition.go
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
package graphql
import (
"context"
"fmt"
"reflect"
"regexp"
"github.com/graphql-go/graphql/language/ast"
)
// Type interface for all of the possible kinds of GraphQL types
type Type interface {
Name() string
Description() string
String() string
Error() error
}
var _ Type = (*Scalar)(nil)
var _ Type = (*Object)(nil)
var _ Type = (*Interface)(nil)
var _ Type = (*Union)(nil)
var _ Type = (*Enum)(nil)
var _ Type = (*InputObject)(nil)
var _ Type = (*List)(nil)
var _ Type = (*NonNull)(nil)
var _ Type = (*Argument)(nil)
// Input interface for types that may be used as input types for arguments and directives.
type Input interface {
Name() string
Description() string
String() string
Error() error
}
var _ Input = (*Scalar)(nil)
var _ Input = (*Enum)(nil)
var _ Input = (*InputObject)(nil)
var _ Input = (*List)(nil)
var _ Input = (*NonNull)(nil)
// IsInputType determines if given type is a GraphQLInputType
func IsInputType(ttype Type) bool {
switch GetNamed(ttype).(type) {
case *Scalar, *Enum, *InputObject:
return true
default:
return false
}
}
// IsOutputType determines if given type is a GraphQLOutputType
func IsOutputType(ttype Type) bool {
switch GetNamed(ttype).(type) {
case *Scalar, *Object, *Interface, *Union, *Enum:
return true
default:
return false
}
}
// Leaf interface for types that may be leaf values
type Leaf interface {
Name() string
Description() string
String() string
Error() error
Serialize(value interface{}) interface{}
}
var _ Leaf = (*Scalar)(nil)
var _ Leaf = (*Enum)(nil)
// IsLeafType determines if given type is a leaf value
func IsLeafType(ttype Type) bool {
switch GetNamed(ttype).(type) {
case *Scalar, *Enum:
return true
default:
return false
}
}
// Output interface for types that may be used as output types as the result of fields.
type Output interface {
Name() string
Description() string
String() string
Error() error
}
var _ Output = (*Scalar)(nil)
var _ Output = (*Object)(nil)
var _ Output = (*Interface)(nil)
var _ Output = (*Union)(nil)
var _ Output = (*Enum)(nil)
var _ Output = (*List)(nil)
var _ Output = (*NonNull)(nil)
// Composite interface for types that may describe the parent context of a selection set.
type Composite interface {
Name() string
Description() string
String() string
Error() error
}
var _ Composite = (*Object)(nil)
var _ Composite = (*Interface)(nil)
var _ Composite = (*Union)(nil)
// IsCompositeType determines if given type is a GraphQLComposite type
func IsCompositeType(ttype interface{}) bool {
switch ttype.(type) {
case *Object, *Interface, *Union:
return true
default:
return false
}
}
// Abstract interface for types that may describe the parent context of a selection set.
type Abstract interface {
Name() string
}
var _ Abstract = (*Interface)(nil)
var _ Abstract = (*Union)(nil)
func IsAbstractType(ttype interface{}) bool {
switch ttype.(type) {
case *Interface, *Union:
return true
default:
return false
}
}
// Nullable interface for types that can accept null as a value.
type Nullable interface {
}
var _ Nullable = (*Scalar)(nil)
var _ Nullable = (*Object)(nil)
var _ Nullable = (*Interface)(nil)
var _ Nullable = (*Union)(nil)
var _ Nullable = (*Enum)(nil)
var _ Nullable = (*InputObject)(nil)
var _ Nullable = (*List)(nil)
// GetNullable returns the Nullable type of the given GraphQL type
func GetNullable(ttype Type) Nullable {
if ttype, ok := ttype.(*NonNull); ok {
return ttype.OfType
}
return ttype
}
// Named interface for types that do not include modifiers like List or NonNull.
type Named interface {
String() string
}
var _ Named = (*Scalar)(nil)
var _ Named = (*Object)(nil)
var _ Named = (*Interface)(nil)
var _ Named = (*Union)(nil)
var _ Named = (*Enum)(nil)
var _ Named = (*InputObject)(nil)
// GetNamed returns the Named type of the given GraphQL type
func GetNamed(ttype Type) Named {
unmodifiedType := ttype
for {
switch typ := unmodifiedType.(type) {
case *List:
unmodifiedType = typ.OfType
case *NonNull:
unmodifiedType = typ.OfType
default:
return unmodifiedType
}
}
}
// Scalar Type Definition
//
// The leaf values of any request and input values to arguments are
// Scalars (or Enums) and are defined with a name and a series of functions
// used to parse input from ast or variables and to ensure validity.
//
// Example:
//
// var OddType = new Scalar({
// name: 'Odd',
// serialize(value) {
// return value % 2 === 1 ? value : null;
// }
// });
type Scalar struct {
PrivateName string `json:"name"`
PrivateDescription string `json:"description"`
scalarConfig ScalarConfig
err error
}
// SerializeFn is a function type for serializing a GraphQLScalar type value
type SerializeFn func(value interface{}) interface{}
// ParseValueFn is a function type for parsing the value of a GraphQLScalar type
type ParseValueFn func(value interface{}) interface{}
// ParseLiteralFn is a function type for parsing the literal value of a GraphQLScalar type
type ParseLiteralFn func(valueAST ast.Value) interface{}
// ScalarConfig options for creating a new GraphQLScalar
type ScalarConfig struct {
Name string `json:"name"`
Description string `json:"description"`
Serialize SerializeFn
ParseValue ParseValueFn
ParseLiteral ParseLiteralFn
}
// NewScalar creates a new GraphQLScalar
func NewScalar(config ScalarConfig) *Scalar {
st := &Scalar{}
err := invariant(config.Name != "", "Type must be named.")
if err != nil {
st.err = err
return st
}
err = assertValidName(config.Name)
if err != nil {
st.err = err
return st
}
st.PrivateName = config.Name
st.PrivateDescription = config.Description
err = invariantf(
config.Serialize != nil,
`%v must provide "serialize" function. If this custom Scalar is `+
`also used as an input type, ensure "parseValue" and "parseLiteral" `+
`functions are also provided.`, st,
)
if err != nil {
st.err = err
return st
}
if config.ParseValue != nil || config.ParseLiteral != nil {
err = invariantf(
config.ParseValue != nil && config.ParseLiteral != nil,
`%v must provide both "parseValue" and "parseLiteral" functions.`, st,
)
if err != nil {
st.err = err
return st
}
}
st.scalarConfig = config
return st
}
func (st *Scalar) Serialize(value interface{}) interface{} {
if st.scalarConfig.Serialize == nil {
return value
}
return st.scalarConfig.Serialize(value)
}
func (st *Scalar) ParseValue(value interface{}) interface{} {
if st.scalarConfig.ParseValue == nil {
return value
}
return st.scalarConfig.ParseValue(value)
}
func (st *Scalar) ParseLiteral(valueAST ast.Value) interface{} {
if st.scalarConfig.ParseLiteral == nil {
return nil
}
return st.scalarConfig.ParseLiteral(valueAST)
}
func (st *Scalar) Name() string {
return st.PrivateName
}
func (st *Scalar) Description() string {
return st.PrivateDescription
}
func (st *Scalar) String() string {
return st.PrivateName
}
func (st *Scalar) Error() error {
return st.err
}
// Object Type Definition
//
// Almost all of the GraphQL types you define will be object Object types
// have a name, but most importantly describe their fields.
// Example:
//
// var AddressType = new Object({
// name: 'Address',
// fields: {
// street: { type: String },
// number: { type: Int },
// formatted: {
// type: String,
// resolve(obj) {
// return obj.number + ' ' + obj.street
// }
// }
// }
// });
//
// When two types need to refer to each other, or a type needs to refer to
// itself in a field, you can use a function expression (aka a closure or a
// thunk) to supply the fields lazily.
//
// Example:
//
// var PersonType = new Object({
// name: 'Person',
// fields: () => ({
// name: { type: String },
// bestFriend: { type: PersonType },
// })
// });
//
// /
type Object struct {
PrivateName string `json:"name"`
PrivateDescription string `json:"description"`
IsTypeOf IsTypeOfFn
typeConfig ObjectConfig
initialisedFields bool
fields FieldDefinitionMap
initialisedInterfaces bool
interfaces []*Interface
// Interim alternative to throwing an error during schema definition at run-time
err error
}
// IsTypeOfParams Params for IsTypeOfFn()
type IsTypeOfParams struct {
// Value that needs to be resolve.
// Use this to decide which GraphQLObject this value maps to.
Value interface{}
// Info is a collection of information about the current execution state.
Info ResolveInfo
// Context argument is a context value that is provided to every resolve function within an execution.
// It is commonly
// used to represent an authenticated user, or request-specific caches.
Context context.Context
}
type IsTypeOfFn func(p IsTypeOfParams) bool
type InterfacesThunk func() []*Interface
type ObjectConfig struct {
Name string `json:"name"`
Interfaces interface{} `json:"interfaces"`
Fields interface{} `json:"fields"`
IsTypeOf IsTypeOfFn `json:"isTypeOf"`
Description string `json:"description"`
}
type FieldsThunk func() Fields
func NewObject(config ObjectConfig) *Object {
objectType := &Object{}
err := invariant(config.Name != "", "Type must be named.")
if err != nil {
objectType.err = err
return objectType
}
err = assertValidName(config.Name)
if err != nil {
objectType.err = err
return objectType
}
objectType.PrivateName = config.Name
objectType.PrivateDescription = config.Description
objectType.IsTypeOf = config.IsTypeOf
objectType.typeConfig = config
return objectType
}
// ensureCache ensures that both fields and interfaces have been initialized properly,
// to prevent races.
func (gt *Object) ensureCache() {
gt.Fields()
gt.Interfaces()
}
func (gt *Object) AddFieldConfig(fieldName string, fieldConfig *Field) {
if fieldName == "" || fieldConfig == nil {
return
}
if fields, ok := gt.typeConfig.Fields.(Fields); ok {
fields[fieldName] = fieldConfig
gt.initialisedFields = false
}
}
func (gt *Object) Name() string {
return gt.PrivateName
}
func (gt *Object) Description() string {
return gt.PrivateDescription
}
func (gt *Object) String() string {
return gt.PrivateName
}
func (gt *Object) Fields() FieldDefinitionMap {
if gt.initialisedFields {
return gt.fields
}
var configureFields Fields
switch fields := gt.typeConfig.Fields.(type) {
case Fields:
configureFields = fields
case FieldsThunk:
configureFields = fields()
}
gt.fields, gt.err = defineFieldMap(gt, configureFields)
gt.initialisedFields = true
return gt.fields
}
func (gt *Object) Interfaces() []*Interface {
if gt.initialisedInterfaces {
return gt.interfaces
}
var configInterfaces []*Interface
switch iface := gt.typeConfig.Interfaces.(type) {
case InterfacesThunk:
configInterfaces = iface()
case []*Interface:
configInterfaces = iface
case nil:
default:
gt.err = fmt.Errorf("Unknown Object.Interfaces type: %T", gt.typeConfig.Interfaces)
gt.initialisedInterfaces = true
return nil
}
gt.interfaces, gt.err = defineInterfaces(gt, configInterfaces)
gt.initialisedInterfaces = true
return gt.interfaces
}
func (gt *Object) Error() error {
return gt.err
}
func defineInterfaces(ttype *Object, interfaces []*Interface) ([]*Interface, error) {
ifaces := []*Interface{}
if len(interfaces) == 0 {
return ifaces, nil
}
for _, iface := range interfaces {
err := invariantf(
iface != nil,
`%v may only implement Interface types, it cannot implement: %v.`, ttype, iface,
)
if err != nil {
return ifaces, err
}
if iface.ResolveType != nil {
err = invariantf(
iface.ResolveType != nil,
`Interface Type %v does not provide a "resolveType" function `+
`and implementing Type %v does not provide a "isTypeOf" `+
`function. There is no way to resolve this implementing type `+
`during execution.`, iface, ttype,
)
if err != nil {
return ifaces, err
}
}
ifaces = append(ifaces, iface)
}
return ifaces, nil
}
func defineFieldMap(ttype Named, fieldMap Fields) (FieldDefinitionMap, error) {
resultFieldMap := FieldDefinitionMap{}
err := invariantf(
len(fieldMap) > 0,
`%v fields must be an object with field names as keys or a function which return such an object.`, ttype,
)
if err != nil {
return resultFieldMap, err
}
for fieldName, field := range fieldMap {
if field == nil {
continue
}
err = invariantf(
field.Type != nil,
`%v.%v field type must be Output Type but got: %v.`, ttype, fieldName, field.Type,
)
if err != nil {
return resultFieldMap, err
}
if field.Type.Error() != nil {
return resultFieldMap, field.Type.Error()
}
if err = assertValidName(fieldName); err != nil {
return resultFieldMap, err
}
fieldDef := &FieldDefinition{
Name: fieldName,
Description: field.Description,
Type: field.Type,
Resolve: field.Resolve,
Subscribe: field.Subscribe,
DeprecationReason: field.DeprecationReason,
}
fieldDef.Args = []*Argument{}
for argName, arg := range field.Args {
if err = assertValidName(argName); err != nil {
return resultFieldMap, err
}
if err = invariantf(
arg != nil,
`%v.%v args must be an object with argument names as keys.`, ttype, fieldName,
); err != nil {
return resultFieldMap, err
}
if err = invariantf(
arg.Type != nil,
`%v.%v(%v:) argument type must be Input Type but got: %v.`, ttype, fieldName, argName, arg.Type,
); err != nil {
return resultFieldMap, err
}
fieldArg := &Argument{
PrivateName: argName,
PrivateDescription: arg.Description,
Type: arg.Type,
DefaultValue: arg.DefaultValue,
}
fieldDef.Args = append(fieldDef.Args, fieldArg)
}
resultFieldMap[fieldName] = fieldDef
}
return resultFieldMap, nil
}
// ResolveParams Params for FieldResolveFn()
type ResolveParams struct {
// Source is the source value
Source interface{}
// Args is a map of arguments for current GraphQL request
Args map[string]interface{}
// Info is a collection of information about the current execution state.
Info ResolveInfo
// Context argument is a context value that is provided to every resolve function within an execution.
// It is commonly
// used to represent an authenticated user, or request-specific caches.
Context context.Context
}
type FieldResolveFn func(p ResolveParams) (interface{}, error)
type ResolveInfo struct {
FieldName string
FieldASTs []*ast.Field
Path *ResponsePath
ReturnType Output
ParentType Composite
Schema Schema
Fragments map[string]ast.Definition
RootValue interface{}
Operation ast.Definition
VariableValues map[string]interface{}
}
type Fields map[string]*Field
type Field struct {
Name string `json:"name"` // used by graphlql-relay
Type Output `json:"type"`
Args FieldConfigArgument `json:"args"`
Resolve FieldResolveFn `json:"-"`
Subscribe FieldResolveFn `json:"-"`
DeprecationReason string `json:"deprecationReason"`
Description string `json:"description"`
}
type FieldConfigArgument map[string]*ArgumentConfig
type ArgumentConfig struct {
Type Input `json:"type"`
DefaultValue interface{} `json:"defaultValue"`
Description string `json:"description"`
}
type FieldDefinitionMap map[string]*FieldDefinition
type FieldDefinition struct {
Name string `json:"name"`
Description string `json:"description"`
Type Output `json:"type"`
Args []*Argument `json:"args"`
Resolve FieldResolveFn `json:"-"`
Subscribe FieldResolveFn `json:"-"`
DeprecationReason string `json:"deprecationReason"`
}
type FieldArgument struct {
Name string `json:"name"`
Type Type `json:"type"`
DefaultValue interface{} `json:"defaultValue"`
Description string `json:"description"`
}
type Argument struct {
PrivateName string `json:"name"`
Type Input `json:"type"`
DefaultValue interface{} `json:"defaultValue"`
PrivateDescription string `json:"description"`
}
func (st *Argument) Name() string {
return st.PrivateName
}
func (st *Argument) Description() string {
return st.PrivateDescription
}
func (st *Argument) String() string {
return st.PrivateName
}
func (st *Argument) Error() error {
return nil
}
// Interface Type Definition
//
// When a field can return one of a heterogeneous set of types, a Interface type
// is used to describe what types are possible, what fields are in common across
// all types, as well as a function to determine which type is actually used
// when the field is resolved.
//
// Example:
//
// var EntityType = new Interface({
// name: 'Entity',
// fields: {
// name: { type: String }
// }
// });
type Interface struct {
PrivateName string `json:"name"`
PrivateDescription string `json:"description"`
ResolveType ResolveTypeFn
typeConfig InterfaceConfig
initialisedFields bool
fields FieldDefinitionMap
err error
}
type InterfaceConfig struct {
Name string `json:"name"`
Fields interface{} `json:"fields"`
ResolveType ResolveTypeFn
Description string `json:"description"`
}
// ResolveTypeParams Params for ResolveTypeFn()
type ResolveTypeParams struct {
// Value that needs to be resolve.
// Use this to decide which GraphQLObject this value maps to.
Value interface{}
// Info is a collection of information about the current execution state.
Info ResolveInfo
// Context argument is a context value that is provided to every resolve function within an execution.
// It is commonly
// used to represent an authenticated user, or request-specific caches.
Context context.Context
}
type ResolveTypeFn func(p ResolveTypeParams) *Object
func NewInterface(config InterfaceConfig) *Interface {
it := &Interface{}
if it.err = invariant(config.Name != "", "Type must be named."); it.err != nil {
return it
}
if it.err = assertValidName(config.Name); it.err != nil {
return it
}
it.PrivateName = config.Name
it.PrivateDescription = config.Description
it.ResolveType = config.ResolveType
it.typeConfig = config
return it
}
func (it *Interface) AddFieldConfig(fieldName string, fieldConfig *Field) {
if fieldName == "" || fieldConfig == nil {
return
}
if fields, ok := it.typeConfig.Fields.(Fields); ok {
fields[fieldName] = fieldConfig
it.initialisedFields = false
}
}
func (it *Interface) Name() string {
return it.PrivateName
}
func (it *Interface) Description() string {
return it.PrivateDescription
}
func (it *Interface) Fields() (fields FieldDefinitionMap) {
if it.initialisedFields {
return it.fields
}
var configureFields Fields
switch fields := it.typeConfig.Fields.(type) {
case Fields:
configureFields = fields
case FieldsThunk:
configureFields = fields()
}
it.fields, it.err = defineFieldMap(it, configureFields)
it.initialisedFields = true
return it.fields
}
func (it *Interface) String() string {
return it.PrivateName
}
func (it *Interface) Error() error {
return it.err
}
// Union Type Definition
//
// When a field can return one of a heterogeneous set of types, a Union type
// is used to describe what types are possible as well as providing a function
// to determine which type is actually used when the field is resolved.
//
// Example:
//
// var PetType = new Union({
// name: 'Pet',
// types: [ DogType, CatType ],
// resolveType(value) {
// if (value instanceof Dog) {
// return DogType;
// }
// if (value instanceof Cat) {
// return CatType;
// }
// }
// });
type Union struct {
PrivateName string `json:"name"`
PrivateDescription string `json:"description"`
ResolveType ResolveTypeFn
typeConfig UnionConfig
initalizedTypes bool
types []*Object
possibleTypes map[string]bool
err error
}
type UnionTypesThunk func() []*Object
type UnionConfig struct {
Name string `json:"name"`
Types interface{} `json:"types"`
ResolveType ResolveTypeFn
Description string `json:"description"`
}
func NewUnion(config UnionConfig) *Union {
objectType := &Union{}
if objectType.err = invariant(config.Name != "", "Type must be named."); objectType.err != nil {
return objectType
}
if objectType.err = assertValidName(config.Name); objectType.err != nil {
return objectType
}
objectType.PrivateName = config.Name
objectType.PrivateDescription = config.Description
objectType.ResolveType = config.ResolveType
objectType.typeConfig = config
return objectType
}
func (ut *Union) Types() []*Object {
if ut.initalizedTypes {
return ut.types
}
var unionTypes []*Object
switch utype := ut.typeConfig.Types.(type) {
case UnionTypesThunk:
unionTypes = utype()
case []*Object:
unionTypes = utype
case nil:
default:
ut.err = fmt.Errorf("Unknown Union.Types type: %T", ut.typeConfig.Types)
ut.initalizedTypes = true
return nil
}
ut.types, ut.err = defineUnionTypes(ut, unionTypes)
ut.initalizedTypes = true
return ut.types
}
func defineUnionTypes(objectType *Union, unionTypes []*Object) ([]*Object, error) {
definedUnionTypes := []*Object{}
if err := invariantf(
len(unionTypes) > 0,
`Must provide Array of types for Union %v.`, objectType.Name(),
); err != nil {
return definedUnionTypes, err
}
for _, ttype := range unionTypes {
if err := invariantf(
ttype != nil,
`%v may only contain Object types, it cannot contain: %v.`, objectType, ttype,
); err != nil {
return definedUnionTypes, err
}
if objectType.ResolveType == nil {
if err := invariantf(
ttype.IsTypeOf != nil,
`Union Type %v does not provide a "resolveType" function `+
`and possible Type %v does not provide a "isTypeOf" `+
`function. There is no way to resolve this possible type `+
`during execution.`, objectType, ttype,
); err != nil {
return definedUnionTypes, err
}
}
definedUnionTypes = append(definedUnionTypes, ttype)
}
return definedUnionTypes, nil
}
func (ut *Union) String() string {
return ut.PrivateName
}
func (ut *Union) Name() string {
return ut.PrivateName
}
func (ut *Union) Description() string {
return ut.PrivateDescription
}
func (ut *Union) Error() error {
return ut.err
}
// Enum Type Definition
//
// Some leaf values of requests and input values are Enums. GraphQL serializes
// Enum values as strings, however internally Enums can be represented by any
// kind of type, often integers.
//
// Example:
//
// var RGBType = new Enum({
// name: 'RGB',
// values: {
// RED: { value: 0 },
// GREEN: { value: 1 },
// BLUE: { value: 2 }
// }
// });
//
// Note: If a value is not provided in a definition, the name of the enum value
// will be used as its internal value.
type Enum struct {
PrivateName string `json:"name"`
PrivateDescription string `json:"description"`
enumConfig EnumConfig
values []*EnumValueDefinition
valuesLookup map[interface{}]*EnumValueDefinition
nameLookup map[string]*EnumValueDefinition
err error
}
type EnumValueConfigMap map[string]*EnumValueConfig
type EnumValueConfig struct {
Value interface{} `json:"value"`
DeprecationReason string `json:"deprecationReason"`
Description string `json:"description"`
}
type EnumConfig struct {
Name string `json:"name"`
Values EnumValueConfigMap `json:"values"`
Description string `json:"description"`
}
type EnumValueDefinition struct {
Name string `json:"name"`
Value interface{} `json:"value"`
DeprecationReason string `json:"deprecationReason"`
Description string `json:"description"`
}
func NewEnum(config EnumConfig) *Enum {
gt := &Enum{}
gt.enumConfig = config
if gt.err = assertValidName(config.Name); gt.err != nil {
return gt
}
gt.PrivateName = config.Name
gt.PrivateDescription = config.Description
if gt.values, gt.err = gt.defineEnumValues(config.Values); gt.err != nil {
return gt
}
return gt
}
func (gt *Enum) defineEnumValues(valueMap EnumValueConfigMap) ([]*EnumValueDefinition, error) {
var err error
values := []*EnumValueDefinition{}
if err = invariantf(
len(valueMap) > 0,
`%v values must be an object with value names as keys.`, gt,
); err != nil {
return values, err
}
for valueName, valueConfig := range valueMap {
if err = invariantf(
valueConfig != nil,
`%v.%v must refer to an object with a "value" key `+
`representing an internal value but got: %v.`, gt, valueName, valueConfig,
); err != nil {
return values, err
}
if err = assertValidName(valueName); err != nil {
return values, err
}
value := &EnumValueDefinition{
Name: valueName,
Value: valueConfig.Value,
DeprecationReason: valueConfig.DeprecationReason,
Description: valueConfig.Description,
}
if value.Value == nil {
value.Value = valueName
}
values = append(values, value)