Debian Codegraph @

src/graphql/utilities/value_from_ast.py

raw
1 from typing import Any, Dict, List, Optional, cast
2
3 from ..language import (
4 ListValueNode,
5 NullValueNode,
6 ObjectValueNode,
7 ValueNode,
8 VariableNode,
9 )
10 from ..pyutils import inspect, Undefined
11 from ..type import (
12 GraphQLInputObjectType,
13 GraphQLInputType,
14 GraphQLList,
15 GraphQLNonNull,
16 GraphQLScalarType,
17 is_input_object_type,
18 is_leaf_type,
19 is_list_type,
20 is_non_null_type,
21 )
22
23 __all__ = ["value_from_ast"]
24
25
26 def value_from_ast(
27 value_node: Optional[ValueNode],
28 type_: GraphQLInputType,
29 variables: Optional[Dict[str, Any]] = None,
30 ) -> Any:
31 """Produce a Python value given a GraphQL Value AST.
32
33 A GraphQL type must be provided, which will be used to interpret different GraphQL
34 Value literals.
35
36 Returns ``Undefined`` when the value could not be validly coerced according
37 to the provided type.
38
39 =================== ============== ================
40 GraphQL Value JSON Value Python Value
41 =================== ============== ================
42 Input Object Object dict
43 List Array list
44 Boolean Boolean bool
45 String String str
46 Int / Float Number int / float
47 Enum Value Mixed Any
48 NullValue null None
49 =================== ============== ================
50
51 """
52 if not value_node:
53 # When there is no node, then there is also no value.
54 # Importantly, this is different from returning the value null.
55 return Undefined
56
57 if isinstance(value_node, VariableNode):
58 variable_name = value_node.name.value
59 if not variables:
60 return Undefined
61 variable_value = variables.get(variable_name, Undefined)
62 if variable_value is None and is_non_null_type(type_):
63 return Undefined
64 # Note: This does no further checking that this variable is correct.
65 # This assumes that this query has been validated and the variable usage here
66 # is of the correct type.
67 return variable_value
68
69 if is_non_null_type(type_):
70 if isinstance(value_node, NullValueNode):
71 return Undefined
72 type_ = cast(GraphQLNonNull, type_)
73 return value_from_ast(value_node, type_.of_type, variables)
74
75 if isinstance(value_node, NullValueNode):
76 return None # This is explicitly returning the value None.
77
78 if is_list_type(type_):
79 type_ = cast(GraphQLList, type_)
80 item_type = type_.of_type
81 if isinstance(value_node, ListValueNode):
82 coerced_values: List[Any] = []
83 append_value = coerced_values.append
84 for item_node in value_node.values:
85 if is_missing_variable(item_node, variables):
86 # If an array contains a missing variable, it is either coerced to
87 # None or if the item type is non-null, it is considered invalid.
88 if is_non_null_type(item_type):
89 return Undefined
90 append_value(None)
91 else:
92 item_value = value_from_ast(item_node, item_type, variables)
93 if item_value is Undefined:
94 return Undefined
95 append_value(item_value)
96 return coerced_values
97 coerced_value = value_from_ast(value_node, item_type, variables)
98 if coerced_value is Undefined:
99 return Undefined
100 return [coerced_value]
101
102 if is_input_object_type(type_):
103 if not isinstance(value_node, ObjectValueNode):
104 return Undefined
105 type_ = cast(GraphQLInputObjectType, type_)
106 coerced_obj: Dict[str, Any] = {}
107 fields = type_.fields
108 field_nodes = {field.name.value: field for field in value_node.fields}
109 for field_name, field in fields.items():
110 field_node = field_nodes.get(field_name)
111 if not field_node or is_missing_variable(field_node.value, variables):
112 if field.default_value is not Undefined:
113 # Use out name as name if it exists (extension of GraphQL.js).
114 coerced_obj[field.out_name or field_name] = field.default_value
115 elif is_non_null_type(field.type): # pragma: no cover else
116 return Undefined
117 continue
118 field_value = value_from_ast(field_node.value, field.type, variables)
119 if field_value is Undefined:
120 return Undefined
121 coerced_obj[field.out_name or field_name] = field_value
122
123 if type_.is_one_of:
124 keys = list(coerced_obj)
125 if len(keys) != 1:
126 return Undefined
127
128 if coerced_obj[keys[0]] is None:
129 return Undefined
130
131 return type_.out_type(coerced_obj)
132
133 if is_leaf_type(type_):
134 # Scalars fulfill parsing a literal value via `parse_literal()`. Invalid values
135 # represent a failure to parse correctly, in which case Undefined is returned.
136 type_ = cast(GraphQLScalarType, type_)
137 # noinspection PyBroadException
138 try:
139 if variables:
140 result = type_.parse_literal(value_node, variables)
141 else:
142 result = type_.parse_literal(value_node)
143 except Exception:
144 return Undefined
145 return result
146
147 # Not reachable. All possible input types have been considered.
148 raise TypeError(f"Unexpected input type: {inspect(type_)}.")
149
150
151 def is_missing_variable(
152 value_node: ValueNode, variables: Optional[Dict[str, Any]] = None
153 ) -> bool:
154 """Check if ``value_node`` is a variable not defined in the ``variables`` dict."""
155 return isinstance(value_node, VariableNode) and (
156 not variables or variables.get(value_node.name.value, Undefined) is Undefined
157 )