-
-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathdefinition.py
More file actions
1614 lines (1325 loc) · 52.6 KB
/
definition.py
File metadata and controls
1614 lines (1325 loc) · 52.6 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
from collections.abc import Sequence as AbstractSequence
from enum import Enum
from typing import (
Any,
Callable,
Dict,
Generic,
List,
NamedTuple,
Optional,
Sequence,
TYPE_CHECKING,
Type,
TypeVar,
Union,
cast,
overload,
)
from ..error import INVALID, InvalidType
from ..language import (
EnumTypeDefinitionNode,
EnumValueDefinitionNode,
EnumTypeExtensionNode,
EnumValueNode,
FieldDefinitionNode,
FieldNode,
FragmentDefinitionNode,
InputObjectTypeDefinitionNode,
InputObjectTypeExtensionNode,
InputValueDefinitionNode,
InterfaceTypeDefinitionNode,
InterfaceTypeExtensionNode,
ObjectTypeDefinitionNode,
ObjectTypeExtensionNode,
OperationDefinitionNode,
ScalarTypeDefinitionNode,
ScalarTypeExtensionNode,
TypeDefinitionNode,
TypeExtensionNode,
UnionTypeDefinitionNode,
UnionTypeExtensionNode,
ValueNode,
)
from ..pyutils import (
AwaitableOrValue,
FrozenList,
Path,
cached_property,
inspect,
is_description,
)
from ..utilities.value_from_ast_untyped import value_from_ast_untyped
if TYPE_CHECKING: # pragma: no cover
from .schema import GraphQLSchema # noqa: F401
__all__ = [
"is_type",
"is_scalar_type",
"is_object_type",
"is_interface_type",
"is_union_type",
"is_enum_type",
"is_input_object_type",
"is_list_type",
"is_non_null_type",
"is_input_type",
"is_output_type",
"is_leaf_type",
"is_composite_type",
"is_abstract_type",
"is_wrapping_type",
"is_nullable_type",
"is_named_type",
"is_required_argument",
"is_required_input_field",
"assert_type",
"assert_scalar_type",
"assert_object_type",
"assert_interface_type",
"assert_union_type",
"assert_enum_type",
"assert_input_object_type",
"assert_list_type",
"assert_non_null_type",
"assert_input_type",
"assert_output_type",
"assert_leaf_type",
"assert_composite_type",
"assert_abstract_type",
"assert_wrapping_type",
"assert_nullable_type",
"assert_named_type",
"get_nullable_type",
"get_named_type",
"GraphQLAbstractType",
"GraphQLArgument",
"GraphQLArgumentMap",
"GraphQLCompositeType",
"GraphQLEnumType",
"GraphQLEnumValue",
"GraphQLEnumValueMap",
"GraphQLField",
"GraphQLFieldMap",
"GraphQLFieldResolver",
"GraphQLInputField",
"GraphQLInputFieldMap",
"GraphQLInputObjectType",
"GraphQLInputType",
"GraphQLInterfaceType",
"GraphQLIsTypeOfFn",
"GraphQLLeafType",
"GraphQLList",
"GraphQLNamedType",
"GraphQLNullableType",
"GraphQLNonNull",
"GraphQLResolveInfo",
"GraphQLScalarType",
"GraphQLScalarSerializer",
"GraphQLScalarValueParser",
"GraphQLScalarLiteralParser",
"GraphQLObjectType",
"GraphQLOutputType",
"GraphQLType",
"GraphQLTypeResolver",
"GraphQLUnionType",
"GraphQLWrappingType",
"Thunk",
]
class GraphQLType:
"""Base class for all GraphQL types"""
# Note: We don't use slots for GraphQLType objects because memory considerations
# are not really important for the schema definition and it would make caching
# properties slower or more complicated.
# There are predicates for each kind of GraphQL type.
def is_type(type_: Any) -> bool:
return isinstance(type_, GraphQLType)
def assert_type(type_: Any) -> GraphQLType:
if not is_type(type_):
raise TypeError(f"Expected {type_} to be a GraphQL type.")
return cast(GraphQLType, type_)
# These types wrap and modify other types
GT = TypeVar("GT", bound=GraphQLType)
class GraphQLWrappingType(GraphQLType, Generic[GT]):
"""Base class for all GraphQL wrapping types"""
of_type: GT
def __init__(self, type_: GT) -> None:
if not is_type(type_):
raise TypeError(
f"Can only create a wrapper for a GraphQLType, but got: {type_}."
)
self.of_type = type_
def __repr__(self):
return f"<{self.__class__.__name__} {self.of_type!r}>"
def is_wrapping_type(type_: Any) -> bool:
return isinstance(type_, GraphQLWrappingType)
def assert_wrapping_type(type_: Any) -> GraphQLWrappingType:
if not is_wrapping_type(type_):
raise TypeError(f"Expected {type_} to be a GraphQL wrapping type.")
return cast(GraphQLWrappingType, type_)
# These named types do not include modifiers like List or NonNull.
class GraphQLNamedType(GraphQLType):
"""Base class for all GraphQL named types"""
name: str
description: Optional[str]
extensions: Optional[Dict[str, Any]]
ast_node: Optional[TypeDefinitionNode]
extension_ast_nodes: Optional[FrozenList[TypeExtensionNode]]
def __init__(
self,
name: str,
description: str = None,
extensions: Dict[str, Any] = None,
ast_node: TypeDefinitionNode = None,
extension_ast_nodes: Sequence[TypeExtensionNode] = None,
) -> None:
if not name:
raise TypeError("Must provide name.")
if not isinstance(name, str):
raise TypeError("The name must be a string.")
if description is not None and not is_description(description):
raise TypeError("The description must be a string.")
if extensions is not None and (
not isinstance(extensions, dict)
or not all(isinstance(key, str) for key in extensions)
):
raise TypeError(f"{name} extensions must be a dictionary with string keys.")
if ast_node and not isinstance(ast_node, TypeDefinitionNode):
raise TypeError(f"{name} AST node must be a TypeDefinitionNode.")
if extension_ast_nodes:
if not isinstance(extension_ast_nodes, AbstractSequence) or not all(
isinstance(node, TypeExtensionNode) for node in extension_ast_nodes
):
raise TypeError(
f"{name} extension AST nodes must be specified"
" as a sequence of TypeExtensionNode instances."
)
if not isinstance(extension_ast_nodes, FrozenList):
extension_ast_nodes = FrozenList(extension_ast_nodes)
else:
extension_ast_nodes = None
self.name = name
self.description = description
self.extensions = extensions
self.ast_node = ast_node
self.extension_ast_nodes = extension_ast_nodes
def __repr__(self):
return f"<{self.__class__.__name__} {self.name!r}>"
def __str__(self):
return self.name
def to_kwargs(self) -> Dict[str, Any]:
return dict(
name=self.name,
description=self.description,
extensions=self.extensions,
ast_node=self.ast_node,
extension_ast_nodes=self.extension_ast_nodes or FrozenList(),
)
def is_named_type(type_: Any) -> bool:
return isinstance(type_, GraphQLNamedType)
def assert_named_type(type_: Any) -> GraphQLNamedType:
if not is_named_type(type_):
raise TypeError(f"Expected {type_} to be a GraphQL named type.")
return cast(GraphQLNamedType, type_)
@overload
def get_named_type(type_: None) -> None:
... # pragma: no cover
@overload # noqa: F811 (pycqa/flake8#423)
def get_named_type(type_: GraphQLType) -> GraphQLNamedType:
... # pragma: no cover
def get_named_type(type_): # noqa: F811
"""Unwrap possible wrapping type"""
if type_:
unwrapped_type = type_
while is_wrapping_type(unwrapped_type):
unwrapped_type = cast(GraphQLWrappingType, unwrapped_type)
unwrapped_type = unwrapped_type.of_type
return cast(GraphQLNamedType, unwrapped_type)
return None
def resolve_thunk(thunk: Any) -> Any:
"""Resolve the given thunk.
Used while defining GraphQL types to allow for circular references in otherwise
immutable type definitions.
"""
return thunk() if callable(thunk) else thunk
# Unfortunately these types cannot be specified any better in Python:
GraphQLScalarSerializer = Callable
GraphQLScalarValueParser = Callable
GraphQLScalarLiteralParser = Callable
class GraphQLScalarType(GraphQLNamedType):
"""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.
If a type's serialize function does not return a value (i.e. it returns `None`),
then no error will be included in the response.
Example:
def serialize_odd(value):
if value % 2 == 1:
return value
odd_type = GraphQLScalarType('Odd', serialize=serialize_odd)
"""
ast_node: Optional[ScalarTypeDefinitionNode]
extension_ast_nodes: Optional[FrozenList[ScalarTypeExtensionNode]]
def __init__(
self,
name: str,
serialize: GraphQLScalarSerializer = None,
parse_value: GraphQLScalarValueParser = None,
parse_literal: GraphQLScalarLiteralParser = None,
description: str = None,
extensions: Dict[str, Any] = None,
ast_node: ScalarTypeDefinitionNode = None,
extension_ast_nodes: Sequence[ScalarTypeExtensionNode] = None,
) -> None:
super().__init__(
name=name,
description=description,
extensions=extensions,
ast_node=ast_node,
extension_ast_nodes=extension_ast_nodes,
)
if serialize is not None and not callable(serialize):
raise TypeError(
f"{name} must provide 'serialize' as a function."
" If this custom Scalar is also used as an input type,"
" ensure 'parse_value' and 'parse_literal' functions"
" are also provided."
)
if parse_literal is not None and (
not callable(parse_literal)
or (parse_value is None or not callable(parse_value))
):
raise TypeError(
f"{name} must provide"
" both 'parse_value' and 'parse_literal' as functions."
)
if ast_node and not isinstance(ast_node, ScalarTypeDefinitionNode):
raise TypeError(f"{name} AST node must be a ScalarTypeDefinitionNode.")
if extension_ast_nodes and not all(
isinstance(node, ScalarTypeExtensionNode) for node in extension_ast_nodes
):
raise TypeError(
f"{name} extension AST nodes must be specified"
" as a sequence of ScalarTypeExtensionNode instances."
)
if serialize is not None:
self.serialize = serialize # type: ignore
if parse_value is not None:
self.parse_value = parse_value # type: ignore
if parse_literal is not None:
self.parse_literal = parse_literal # type: ignore
def __repr__(self):
return f"<{self.__class__.__name__} {self.name!r}>"
def __str__(self):
return self.name
@staticmethod
def serialize(value: Any) -> Any:
"""Serializes an internal value to include in a response.
This default method just passes the value through and should be replaced
with a more specific version when creating a scalar type.
"""
return value
@staticmethod
def parse_value(value: Any) -> Any:
"""Parses an externally provided value to use as an input.
This default method just passes the value through and should be replaced
with a more specific version when creating a scalar type.
"""
return value
def parse_literal(self, node: ValueNode, _variables: Dict[str, Any] = None) -> Any:
"""Parses an externally provided literal value to use as an input.
This default method uses the parse_value method and should be replaced
with a more specific version when creating a scalar type.
"""
return self.parse_value(value_from_ast_untyped(node))
def to_kwargs(self) -> Dict[str, Any]:
return dict(
**super().to_kwargs(),
serialize=None
if self.serialize is GraphQLScalarType.serialize
else self.serialize,
parse_value=None
if self.parse_value is GraphQLScalarType.parse_value
else self.parse_value,
parse_literal=None
if getattr(self.parse_literal, "__func__", None)
is GraphQLScalarType.parse_literal
else self.parse_literal,
)
def is_scalar_type(type_: Any) -> bool:
return isinstance(type_, GraphQLScalarType)
def assert_scalar_type(type_: Any) -> GraphQLScalarType:
if not is_scalar_type(type_):
raise TypeError(f"Expected {type_} to be a GraphQL Scalar type.")
return cast(GraphQLScalarType, type_)
GraphQLArgumentMap = Dict[str, "GraphQLArgument"]
class GraphQLField:
"""Definition of a GraphQL field"""
type: "GraphQLOutputType"
args: GraphQLArgumentMap
resolve: Optional["GraphQLFieldResolver"]
subscribe: Optional["GraphQLFieldResolver"]
description: Optional[str]
deprecation_reason: Optional[str]
extensions: Optional[Dict[str, Any]]
ast_node: Optional[FieldDefinitionNode]
def __init__(
self,
type_: "GraphQLOutputType",
args: GraphQLArgumentMap = None,
resolve: "GraphQLFieldResolver" = None,
subscribe: "GraphQLFieldResolver" = None,
description: str = None,
deprecation_reason: str = None,
extensions: Dict[str, Any] = None,
ast_node: FieldDefinitionNode = None,
) -> None:
if not is_output_type(type_):
raise TypeError("Field type must be an output type.")
if args is None:
args = {}
elif not isinstance(args, dict):
raise TypeError("Field args must be a dict with argument names as keys.")
elif not all(
isinstance(value, GraphQLArgument) or is_input_type(value)
for value in args.values()
):
raise TypeError(
"Field args must be GraphQLArguments or input type objects."
)
else:
args = {
name: value
if isinstance(value, GraphQLArgument)
else GraphQLArgument(cast(GraphQLInputType, value))
for name, value in args.items()
}
if resolve is not None and not callable(resolve):
raise TypeError(
"Field resolver must be a function if provided, "
f" but got: {inspect(resolve)}."
)
if description is not None and not is_description(description):
raise TypeError("The description must be a string.")
if deprecation_reason is not None and not is_description(deprecation_reason):
raise TypeError("The deprecation reason must be a string.")
if extensions is not None and (
not isinstance(extensions, dict)
or not all(isinstance(key, str) for key in extensions)
):
raise TypeError("Field extensions must be a dictionary with string keys.")
if ast_node and not isinstance(ast_node, FieldDefinitionNode):
raise TypeError("Field AST node must be a FieldDefinitionNode.")
self.type = type_
self.args = args or {}
self.resolve = resolve
self.subscribe = subscribe
self.description = description
self.deprecation_reason = deprecation_reason
self.extensions = extensions
self.ast_node = ast_node
def __repr__(self):
return f"<{self.__class__.__name__} {self.type!r}>"
def __str__(self):
return f"Field: {self.type}"
def __eq__(self, other):
return self is other or (
isinstance(other, GraphQLField)
and self.type == other.type
and self.args == other.args
and self.resolve == other.resolve
and self.description == other.description
and self.deprecation_reason == other.deprecation_reason
and self.extensions == other.extensions
)
def to_kwargs(self) -> Dict[str, Any]:
return dict(
type_=self.type,
args=self.args.copy() if self.args else None,
resolve=self.resolve,
subscribe=self.subscribe,
deprecation_reason=self.deprecation_reason,
description=self.description,
extensions=self.extensions,
ast_node=self.ast_node,
)
@property
def is_deprecated(self) -> bool:
return bool(self.deprecation_reason)
class GraphQLResolveInfo(NamedTuple):
"""Collection of information passed to the resolvers.
This is always passed as the first argument to the resolvers.
Note that contrary to the JavaScript implementation, the context (commonly used to
represent an authenticated user, or request-specific caches) is included here and
not passed as an additional argument.
"""
field_name: str
field_nodes: List[FieldNode]
return_type: "GraphQLOutputType"
parent_type: "GraphQLObjectType"
path: Path
schema: "GraphQLSchema"
fragments: Dict[str, FragmentDefinitionNode]
root_value: Any
operation: OperationDefinitionNode
variable_values: Dict[str, Any]
context: Any
# Note: Contrary to the Javascript implementation of GraphQLFieldResolver,
# the context is passed as part of the GraphQLResolveInfo and any arguments
# are passed individually as keyword arguments.
GraphQLFieldResolverWithoutArgs = Callable[[Any, GraphQLResolveInfo], Any]
# Unfortunately there is currently no syntax to indicate optional or keyword
# arguments in Python, so we also allow any other Callable as a workaround:
GraphQLFieldResolver = Callable[..., Any]
# Note: Contrary to the Javascript implementation of GraphQLTypeResolver,
# the context is passed as part of the GraphQLResolveInfo:
GraphQLTypeResolver = Callable[
[Any, GraphQLResolveInfo, "GraphQLAbstractType"],
AwaitableOrValue[Optional[Union["GraphQLObjectType", str]]],
]
# Note: Contrary to the Javascript implementation of GraphQLIsTypeOfFn,
# the context is passed as part of the GraphQLResolveInfo:
GraphQLIsTypeOfFn = Callable[[Any, GraphQLResolveInfo], AwaitableOrValue[bool]]
class GraphQLArgument:
"""Definition of a GraphQL argument"""
type: "GraphQLInputType"
default_value: Any
description: Optional[str]
out_name: Optional[str] # for transforming names (extension of GraphQL.js)
extensions: Optional[Dict[str, Any]]
ast_node: Optional[InputValueDefinitionNode]
def __init__(
self,
type_: "GraphQLInputType",
default_value: Any = INVALID,
description: str = None,
out_name: str = None,
extensions: Dict[str, Any] = None,
ast_node: InputValueDefinitionNode = None,
) -> None:
if not is_input_type(type_):
raise TypeError(f"Argument type must be a GraphQL input type.")
if description is not None and not is_description(description):
raise TypeError("Argument description must be a string.")
if out_name is not None and not isinstance(out_name, str):
raise TypeError("Argument out name must be a string.")
if extensions is not None and (
not isinstance(extensions, dict)
or not all(isinstance(key, str) for key in extensions)
):
raise TypeError(
"Argument extensions must be a dictionary with string keys."
)
if ast_node and not isinstance(ast_node, InputValueDefinitionNode):
raise TypeError("Argument AST node must be an InputValueDefinitionNode.")
self.type = type_
self.default_value = default_value
self.description = description
self.out_name = out_name
self.extensions = extensions
self.ast_node = ast_node
def __eq__(self, other):
return self is other or (
isinstance(other, GraphQLArgument)
and self.type == other.type
and self.default_value == other.default_value
and self.description == other.description
and self.out_name == other.out_name
and self.extensions == other.extensions
)
def to_kwargs(self) -> Dict[str, Any]:
return dict(
type_=self.type,
default_value=self.default_value,
description=self.description,
out_name=self.out_name,
extensions=self.extensions,
ast_node=self.ast_node,
)
def is_required_argument(arg: GraphQLArgument) -> bool:
return is_non_null_type(arg.type) and arg.default_value is INVALID
T = TypeVar("T")
Thunk = Union[Callable[[], T], T]
GraphQLFieldMap = Dict[str, GraphQLField]
class GraphQLObjectType(GraphQLNamedType):
"""Object Type Definition
Almost all of the GraphQL types you define will be object types. Object types have
a name, but most importantly describe their fields.
Example::
AddressType = GraphQLObjectType('Address', {
'street': GraphQLField(GraphQLString),
'number': GraphQLField(GraphQLInt),
'formatted': GraphQLField(GraphQLString,
lambda obj, info, **args: f'{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 lambda function with no arguments (a so-called "thunk")
to supply the fields lazily.
Example::
PersonType = GraphQLObjectType('Person', lambda: {
'name': GraphQLField(GraphQLString),
'bestFriend': GraphQLField(PersonType)
})
"""
is_type_of: Optional[GraphQLIsTypeOfFn]
ast_node: Optional[ObjectTypeDefinitionNode]
extension_ast_nodes: Optional[FrozenList[ObjectTypeExtensionNode]]
def __init__(
self,
name: str,
fields: Thunk[GraphQLFieldMap],
interfaces: Thunk[Sequence["GraphQLInterfaceType"]] = None,
is_type_of: GraphQLIsTypeOfFn = None,
extensions: Dict[str, Any] = None,
description: str = None,
ast_node: ObjectTypeDefinitionNode = None,
extension_ast_nodes: Sequence[ObjectTypeExtensionNode] = None,
) -> None:
super().__init__(
name=name,
description=description,
extensions=extensions,
ast_node=ast_node,
extension_ast_nodes=extension_ast_nodes,
)
if is_type_of is not None and not callable(is_type_of):
raise TypeError(
f"{name} must provide 'is_type_of' as a function,"
f" but got: {inspect(is_type_of)}."
)
if ast_node and not isinstance(ast_node, ObjectTypeDefinitionNode):
raise TypeError(f"{name} AST node must be an ObjectTypeDefinitionNode.")
if extension_ast_nodes and not all(
isinstance(node, ObjectTypeExtensionNode) for node in extension_ast_nodes
):
raise TypeError(
f"{name} extension AST nodes must be specified"
" as a sequence of ObjectTypeExtensionNode instances."
)
self._fields = fields
self._interfaces = interfaces
self.is_type_of = is_type_of
def to_kwargs(self) -> Dict[str, Any]:
return dict(
**super().to_kwargs(),
fields=self.fields.copy(),
interfaces=self.interfaces,
is_type_of=self.is_type_of,
)
@cached_property
def fields(self) -> GraphQLFieldMap:
"""Get provided fields, wrapping them as GraphQLFields if needed."""
try:
fields = resolve_thunk(self._fields)
except Exception as error:
raise TypeError(f"{self.name} fields cannot be resolved: {error}")
if not isinstance(fields, dict) or not all(
isinstance(key, str) for key in fields
):
raise TypeError(
f"{self.name} fields must be specified"
" as a dict with field names as keys."
)
if not all(
isinstance(value, GraphQLField) or is_output_type(value)
for value in fields.values()
):
raise TypeError(
f"{self.name} fields must be GraphQLField or output type objects."
)
return {
name: value if isinstance(value, GraphQLField) else GraphQLField(value)
for name, value in fields.items()
}
@cached_property
def interfaces(self) -> List["GraphQLInterfaceType"]:
"""Get provided interfaces."""
try:
interfaces: Sequence["GraphQLInterfaceType"] = resolve_thunk(
self._interfaces
)
except Exception as error:
raise TypeError(f"{self.name} interfaces cannot be resolved: {error}")
if interfaces is None:
interfaces = []
elif not isinstance(interfaces, AbstractSequence) or not all(
isinstance(value, GraphQLInterfaceType) for value in interfaces
):
raise TypeError(
f"{self.name} interfaces must be specified"
" as a sequence of GraphQLInterfaceType instances."
)
return list(interfaces)
def is_object_type(type_: Any) -> bool:
return isinstance(type_, GraphQLObjectType)
def assert_object_type(type_: Any) -> GraphQLObjectType:
if not is_object_type(type_):
raise TypeError(f"Expected {type_} to be a GraphQL Object type.")
return cast(GraphQLObjectType, type_)
class GraphQLInterfaceType(GraphQLNamedType):
"""Interface Type Definition
When a field can return one of a heterogeneous set of types, an 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::
EntityType = GraphQLInterfaceType('Entity', {
'name': GraphQLField(GraphQLString),
})
"""
resolve_type: Optional[GraphQLTypeResolver]
ast_node: Optional[InterfaceTypeDefinitionNode]
extension_ast_nodes: Optional[FrozenList[InterfaceTypeExtensionNode]]
def __init__(
self,
name: str,
fields: Thunk[GraphQLFieldMap] = None,
resolve_type: GraphQLTypeResolver = None,
description: str = None,
extensions: Dict[str, Any] = None,
ast_node: InterfaceTypeDefinitionNode = None,
extension_ast_nodes: Sequence[InterfaceTypeExtensionNode] = None,
) -> None:
super().__init__(
name=name,
description=description,
extensions=extensions,
ast_node=ast_node,
extension_ast_nodes=extension_ast_nodes,
)
if resolve_type is not None and not callable(resolve_type):
raise TypeError(
f"{name} must provide 'resolve_type' as a function,"
f" but got: {inspect(resolve_type)}."
)
if ast_node and not isinstance(ast_node, InterfaceTypeDefinitionNode):
raise TypeError(f"{name} AST node must be an InterfaceTypeDefinitionNode.")
if extension_ast_nodes and not all(
isinstance(node, InterfaceTypeExtensionNode) for node in extension_ast_nodes
):
raise TypeError(
f"{name} extension AST nodes must be specified"
" as a sequence of InterfaceTypeExtensionNode instances."
)
self._fields = fields
self.resolve_type = resolve_type
def to_kwargs(self) -> Dict[str, Any]:
return dict(
**super().to_kwargs(),
fields=self.fields.copy(),
resolve_type=self.resolve_type,
)
@cached_property
def fields(self) -> GraphQLFieldMap:
"""Get provided fields, wrapping them as GraphQLFields if needed."""
try:
fields = resolve_thunk(self._fields)
except Exception as error:
raise TypeError(f"{self.name} fields cannot be resolved: {error}")
if not isinstance(fields, dict) or not all(
isinstance(key, str) for key in fields
):
raise TypeError(
f"{self.name} fields must be specified"
" as a dict with field names as keys."
)
if not all(
isinstance(value, GraphQLField) or is_output_type(value)
for value in fields.values()
):
raise TypeError(
f"{self.name} fields must be GraphQLField or output type objects."
)
return {
name: value if isinstance(value, GraphQLField) else GraphQLField(value)
for name, value in fields.items()
}
def is_interface_type(type_: Any) -> bool:
return isinstance(type_, GraphQLInterfaceType)
def assert_interface_type(type_: Any) -> GraphQLInterfaceType:
if not is_interface_type(type_):
raise TypeError(f"Expected {type_} to be a GraphQL Interface type.")
return cast(GraphQLInterfaceType, type_)
class GraphQLUnionType(GraphQLNamedType):
"""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:
class PetType(GraphQLUnionType):
name = 'Pet'
types = [DogType, CatType]
def resolve_type(self, value, _type):
if isinstance(value, Dog):
return DogType()
if isinstance(value, Cat):
return CatType()
"""
resolve_type: Optional[GraphQLTypeResolver]
ast_node: Optional[UnionTypeDefinitionNode]
extension_ast_nodes: Optional[FrozenList[UnionTypeExtensionNode]]
def __init__(
self,
name,
types: Thunk[Sequence[GraphQLObjectType]],
resolve_type: GraphQLTypeResolver = None,
description: str = None,
extensions: Dict[str, Any] = None,
ast_node: UnionTypeDefinitionNode = None,
extension_ast_nodes: Sequence[UnionTypeExtensionNode] = None,
) -> None:
super().__init__(
name=name,
description=description,
extensions=extensions,
ast_node=ast_node,
extension_ast_nodes=extension_ast_nodes,
)
if resolve_type is not None and not callable(resolve_type):
raise TypeError(
f"{name} must provide 'resolve_type' as a function,"
f" but got: {inspect(resolve_type)}."
)
if ast_node and not isinstance(ast_node, UnionTypeDefinitionNode):
raise TypeError(f"{name} AST node must be a UnionTypeDefinitionNode.")
if extension_ast_nodes and not all(
isinstance(node, UnionTypeExtensionNode) for node in extension_ast_nodes
):
raise TypeError(
f"{name} extension AST nodes must be specified"
" as a sequence of UnionTypeExtensionNode instances."
)
self._types = types
self.resolve_type = resolve_type
def to_kwargs(self) -> Dict[str, Any]:
return dict(
**super().to_kwargs(), types=self.types, resolve_type=self.resolve_type
)
@cached_property
def types(self) -> List[GraphQLObjectType]:
"""Get provided types."""
try:
types: Sequence[GraphQLObjectType] = resolve_thunk(self._types)
except Exception as error:
raise TypeError(f"{self.name} types cannot be resolved: {error}")
if types is None:
types = []
elif not isinstance(types, AbstractSequence) or not all(
isinstance(value, GraphQLObjectType) for value in types
):
raise TypeError(
f"{self.name} types must be specified"
" as a sequence of GraphQLObjectType instances."
)
return list(types)
def is_union_type(type_: Any) -> bool:
return isinstance(type_, GraphQLUnionType)
def assert_union_type(type_: Any) -> GraphQLUnionType:
if not is_union_type(type_):
raise TypeError(f"Expected {type_} to be a GraphQL Union type.")
return cast(GraphQLUnionType, type_)
GraphQLEnumValueMap = Dict[str, "GraphQLEnumValue"]
class GraphQLEnumType(GraphQLNamedType):
"""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. They can also be provided as a Python Enum.
Example::
RGBType = GraphQLEnumType('RGB', {
'RED': 0,
'GREEN': 1,
'BLUE': 2
})
Example using a Python Enum::
class RGBEnum(enum.Enum):
RED = 0
GREEN = 1
BLUE = 2
RGBType = GraphQLEnumType('RGB', enum.Enum)
Instead of raw values, you can also specify GraphQLEnumValue objects with more
detail like description or deprecation information.
Note: If a value is not provided in a definition, the name of the enum value will