Debian Codegraph @

src/graphql/utilities/build_client_schema.py

raw
1 from itertools import chain
2 from typing import cast, Callable, Collection, Dict, List, Union
3
4 from ..language import DirectiveLocation, parse_value
5 from ..pyutils import inspect, Undefined
6 from ..type import (
7 GraphQLArgument,
8 GraphQLDirective,
9 GraphQLEnumType,
10 GraphQLEnumValue,
11 GraphQLField,
12 GraphQLInputField,
13 GraphQLInputObjectType,
14 GraphQLInputType,
15 GraphQLInterfaceType,
16 GraphQLList,
17 GraphQLNamedType,
18 GraphQLNonNull,
19 GraphQLObjectType,
20 GraphQLOutputType,
21 GraphQLScalarType,
22 GraphQLSchema,
23 GraphQLType,
24 GraphQLUnionType,
25 TypeKind,
26 assert_interface_type,
27 assert_nullable_type,
28 assert_object_type,
29 introspection_types,
30 is_input_type,
31 is_output_type,
32 specified_scalar_types,
33 )
34 from .get_introspection_query import (
35 IntrospectionDirective,
36 IntrospectionEnumType,
37 IntrospectionField,
38 IntrospectionInterfaceType,
39 IntrospectionInputObjectType,
40 IntrospectionInputValue,
41 IntrospectionObjectType,
42 IntrospectionQuery,
43 IntrospectionScalarType,
44 IntrospectionType,
45 IntrospectionTypeRef,
46 IntrospectionUnionType,
47 )
48 from .value_from_ast import value_from_ast
49
50 __all__ = ["build_client_schema"]
51
52
53 def build_client_schema(
54 introspection: IntrospectionQuery, assume_valid: bool = False
55 ) -> GraphQLSchema:
56 """Build a GraphQLSchema for use by client tools.
57
58 Given the result of a client running the introspection query, creates and returns
59 a GraphQLSchema instance which can be then used with all GraphQL-core 3 tools,
60 but cannot be used to execute a query, as introspection does not represent the
61 "resolver", "parse" or "serialize" functions or any other server-internal
62 mechanisms.
63
64 This function expects a complete introspection result. Don't forget to check the
65 "errors" field of a server response before calling this function.
66 """
67 if not isinstance(introspection, dict) or not isinstance(
68 introspection.get("__schema"), dict
69 ):
70 raise TypeError(
71 "Invalid or incomplete introspection result. Ensure that you"
72 " are passing the 'data' attribute of an introspection response"
73 f" and no 'errors' were returned alongside: {inspect(introspection)}."
74 )
75
76 # Get the schema from the introspection result.
77 schema_introspection = introspection["__schema"]
78
79 # Given a type reference in introspection, return the GraphQLType instance,
80 # preferring cached instances before building new instances.
81 def get_type(type_ref: IntrospectionTypeRef) -> GraphQLType:
82 kind = type_ref.get("kind")
83 if kind == TypeKind.LIST.name:
84 item_ref = type_ref.get("ofType")
85 if not item_ref:
86 raise TypeError("Decorated type deeper than introspection query.")
87 item_ref = cast(IntrospectionTypeRef, item_ref)
88 return GraphQLList(get_type(item_ref))
89 if kind == TypeKind.NON_NULL.name:
90 nullable_ref = type_ref.get("ofType")
91 if not nullable_ref:
92 raise TypeError("Decorated type deeper than introspection query.")
93 nullable_ref = cast(IntrospectionTypeRef, nullable_ref)
94 nullable_type = get_type(nullable_ref)
95 return GraphQLNonNull(assert_nullable_type(nullable_type))
96 type_ref = cast(IntrospectionType, type_ref)
97 return get_named_type(type_ref)
98
99 def get_named_type(type_ref: IntrospectionType) -> GraphQLNamedType:
100 type_name = type_ref.get("name")
101 if not type_name:
102 raise TypeError(f"Unknown type reference: {inspect(type_ref)}.")
103
104 type_ = type_map.get(type_name)
105 if not type_:
106 raise TypeError(
107 f"Invalid or incomplete schema, unknown type: {type_name}."
108 " Ensure that a full introspection query is used in order"
109 " to build a client schema."
110 )
111 return type_
112
113 def get_object_type(type_ref: IntrospectionObjectType) -> GraphQLObjectType:
114 return assert_object_type(get_type(type_ref))
115
116 def get_interface_type(
117 type_ref: IntrospectionInterfaceType,
118 ) -> GraphQLInterfaceType:
119 return assert_interface_type(get_type(type_ref))
120
121 # Given a type's introspection result, construct the correct GraphQLType instance.
122 def build_type(type_: IntrospectionType) -> GraphQLNamedType:
123 if type_ and "name" in type_ and "kind" in type_:
124 builder = type_builders.get(type_["kind"])
125 if builder: # pragma: no cover else
126 return builder(type_)
127 raise TypeError(
128 "Invalid or incomplete introspection result."
129 " Ensure that a full introspection query is used in order"
130 f" to build a client schema: {inspect(type_)}."
131 )
132
133 def build_scalar_def(
134 scalar_introspection: IntrospectionScalarType,
135 ) -> GraphQLScalarType:
136 name = scalar_introspection["name"]
137 try:
138 return cast(GraphQLScalarType, GraphQLScalarType.reserved_types[name])
139 except KeyError:
140 return GraphQLScalarType(
141 name=name,
142 description=scalar_introspection.get("description"),
143 specified_by_url=scalar_introspection.get("specifiedByURL"),
144 )
145
146 def build_implementations_list(
147 implementing_introspection: Union[
148 IntrospectionObjectType, IntrospectionInterfaceType
149 ],
150 ) -> List[GraphQLInterfaceType]:
151 maybe_interfaces = implementing_introspection.get("interfaces")
152 if maybe_interfaces is None:
153 # Temporary workaround until GraphQL ecosystem will fully support
154 # 'interfaces' on interface types
155 if implementing_introspection["kind"] == TypeKind.INTERFACE.name:
156 return []
157 raise TypeError(
158 "Introspection result missing interfaces:"
159 f" {inspect(implementing_introspection)}."
160 )
161 interfaces = cast(Collection[IntrospectionInterfaceType], maybe_interfaces)
162 return [get_interface_type(interface) for interface in interfaces]
163
164 def build_object_def(
165 object_introspection: IntrospectionObjectType,
166 ) -> GraphQLObjectType:
167 name = object_introspection["name"]
168 try:
169 return cast(GraphQLObjectType, GraphQLObjectType.reserved_types[name])
170 except KeyError:
171 return GraphQLObjectType(
172 name=name,
173 description=object_introspection.get("description"),
174 interfaces=lambda: build_implementations_list(object_introspection),
175 fields=lambda: build_field_def_map(object_introspection),
176 )
177
178 def build_interface_def(
179 interface_introspection: IntrospectionInterfaceType,
180 ) -> GraphQLInterfaceType:
181 return GraphQLInterfaceType(
182 name=interface_introspection["name"],
183 description=interface_introspection.get("description"),
184 interfaces=lambda: build_implementations_list(interface_introspection),
185 fields=lambda: build_field_def_map(interface_introspection),
186 )
187
188 def build_union_def(
189 union_introspection: IntrospectionUnionType,
190 ) -> GraphQLUnionType:
191 maybe_possible_types = union_introspection.get("possibleTypes")
192 if maybe_possible_types is None:
193 raise TypeError(
194 "Introspection result missing possibleTypes:"
195 f" {inspect(union_introspection)}."
196 )
197 possible_types = cast(Collection[IntrospectionObjectType], maybe_possible_types)
198 return GraphQLUnionType(
199 name=union_introspection["name"],
200 description=union_introspection.get("description"),
201 types=lambda: [get_object_type(type_) for type_ in possible_types],
202 )
203
204 def build_enum_def(enum_introspection: IntrospectionEnumType) -> GraphQLEnumType:
205 if enum_introspection.get("enumValues") is None:
206 raise TypeError(
207 "Introspection result missing enumValues:"
208 f" {inspect(enum_introspection)}."
209 )
210 name = enum_introspection["name"]
211 try:
212 return cast(GraphQLEnumType, GraphQLEnumType.reserved_types[name])
213 except KeyError:
214 return GraphQLEnumType(
215 name=name,
216 description=enum_introspection.get("description"),
217 values={
218 value_introspect["name"]: GraphQLEnumValue(
219 value=value_introspect["name"],
220 description=value_introspect.get("description"),
221 deprecation_reason=value_introspect.get("deprecationReason"),
222 )
223 for value_introspect in enum_introspection["enumValues"]
224 },
225 )
226
227 def build_input_object_def(
228 input_object_introspection: IntrospectionInputObjectType,
229 ) -> GraphQLInputObjectType:
230 if input_object_introspection.get("inputFields") is None:
231 raise TypeError(
232 "Introspection result missing inputFields:"
233 f" {inspect(input_object_introspection)}."
234 )
235 return GraphQLInputObjectType(
236 name=input_object_introspection["name"],
237 description=input_object_introspection.get("description"),
238 fields=lambda: build_input_value_def_map(
239 input_object_introspection["inputFields"]
240 ),
241 is_one_of=input_object_introspection.get("isOneOf", False),
242 )
243
244 type_builders: Dict[str, Callable[[IntrospectionType], GraphQLNamedType]] = {
245 TypeKind.SCALAR.name: build_scalar_def, # type: ignore
246 TypeKind.OBJECT.name: build_object_def, # type: ignore
247 TypeKind.INTERFACE.name: build_interface_def, # type: ignore
248 TypeKind.UNION.name: build_union_def, # type: ignore
249 TypeKind.ENUM.name: build_enum_def, # type: ignore
250 TypeKind.INPUT_OBJECT.name: build_input_object_def, # type: ignore
251 }
252
253 def build_field_def_map(
254 type_introspection: Union[IntrospectionObjectType, IntrospectionInterfaceType],
255 ) -> Dict[str, GraphQLField]:
256 if type_introspection.get("fields") is None:
257 raise TypeError(
258 f"Introspection result missing fields: {type_introspection}."
259 )
260 return {
261 field_introspection["name"]: build_field(field_introspection)
262 for field_introspection in type_introspection["fields"]
263 }
264
265 def build_field(field_introspection: IntrospectionField) -> GraphQLField:
266 type_introspection = cast(IntrospectionType, field_introspection["type"])
267 type_ = get_type(type_introspection)
268 if not is_output_type(type_):
269 raise TypeError(
270 "Introspection must provide output type for fields,"
271 f" but received: {inspect(type_)}."
272 )
273 type_ = cast(GraphQLOutputType, type_)
274
275 args_introspection = field_introspection.get("args")
276 if args_introspection is None:
277 raise TypeError(
278 "Introspection result missing field args:"
279 f" {inspect(field_introspection)}."
280 )
281
282 return GraphQLField(
283 type_,
284 args=build_argument_def_map(args_introspection),
285 description=field_introspection.get("description"),
286 deprecation_reason=field_introspection.get("deprecationReason"),
287 )
288
289 def build_argument_def_map(
290 argument_value_introspections: Collection[IntrospectionInputValue],
291 ) -> Dict[str, GraphQLArgument]:
292 return {
293 argument_introspection["name"]: build_argument(argument_introspection)
294 for argument_introspection in argument_value_introspections
295 }
296
297 def build_argument(
298 argument_introspection: IntrospectionInputValue,
299 ) -> GraphQLArgument:
300 type_introspection = cast(IntrospectionType, argument_introspection["type"])
301 type_ = get_type(type_introspection)
302 if not is_input_type(type_):
303 raise TypeError(
304 "Introspection must provide input type for arguments,"
305 f" but received: {inspect(type_)}."
306 )
307 type_ = cast(GraphQLInputType, type_)
308
309 default_value_introspection = argument_introspection.get("defaultValue")
310 default_value = (
311 Undefined
312 if default_value_introspection is None
313 else value_from_ast(parse_value(default_value_introspection), type_)
314 )
315 return GraphQLArgument(
316 type_,
317 default_value=default_value,
318 description=argument_introspection.get("description"),
319 deprecation_reason=argument_introspection.get("deprecationReason"),
320 )
321
322 def build_input_value_def_map(
323 input_value_introspections: Collection[IntrospectionInputValue],
324 ) -> Dict[str, GraphQLInputField]:
325 return {
326 input_value_introspection["name"]: build_input_value(
327 input_value_introspection
328 )
329 for input_value_introspection in input_value_introspections
330 }
331
332 def build_input_value(
333 input_value_introspection: IntrospectionInputValue,
334 ) -> GraphQLInputField:
335 type_introspection = cast(IntrospectionType, input_value_introspection["type"])
336 type_ = get_type(type_introspection)
337 if not is_input_type(type_):
338 raise TypeError(
339 "Introspection must provide input type for input fields,"
340 f" but received: {inspect(type_)}."
341 )
342 type_ = cast(GraphQLInputType, type_)
343
344 default_value_introspection = input_value_introspection.get("defaultValue")
345 default_value = (
346 Undefined
347 if default_value_introspection is None
348 else value_from_ast(parse_value(default_value_introspection), type_)
349 )
350 return GraphQLInputField(
351 type_,
352 default_value=default_value,
353 description=input_value_introspection.get("description"),
354 deprecation_reason=input_value_introspection.get("deprecationReason"),
355 )
356
357 def build_directive(
358 directive_introspection: IntrospectionDirective,
359 ) -> GraphQLDirective:
360 if directive_introspection.get("args") is None:
361 raise TypeError(
362 "Introspection result missing directive args:"
363 f" {inspect(directive_introspection)}."
364 )
365 if directive_introspection.get("locations") is None:
366 raise TypeError(
367 "Introspection result missing directive locations:"
368 f" {inspect(directive_introspection)}."
369 )
370 return GraphQLDirective(
371 name=directive_introspection["name"],
372 description=directive_introspection.get("description"),
373 is_repeatable=directive_introspection.get("isRepeatable", False),
374 deprecation_reason=directive_introspection.get("deprecationReason"),
375 locations=list(
376 cast(
377 Collection[DirectiveLocation],
378 directive_introspection.get("locations"),
379 )
380 ),
381 args=build_argument_def_map(directive_introspection["args"]),
382 )
383
384 # Iterate through all types, getting the type definition for each.
385 type_map: Dict[str, GraphQLNamedType] = {
386 type_introspection["name"]: build_type(type_introspection)
387 for type_introspection in schema_introspection["types"]
388 }
389
390 # Include standard types only if they are used.
391 for std_type_name, std_type in chain(
392 specified_scalar_types.items(), introspection_types.items()
393 ):
394 if std_type_name in type_map:
395 type_map[std_type_name] = std_type
396
397 # Get the root Query, Mutation, and Subscription types.
398 query_type_ref = schema_introspection.get("queryType")
399 query_type = None if query_type_ref is None else get_object_type(query_type_ref)
400 mutation_type_ref = schema_introspection.get("mutationType")
401 mutation_type = (
402 None if mutation_type_ref is None else get_object_type(mutation_type_ref)
403 )
404 subscription_type_ref = schema_introspection.get("subscriptionType")
405 subscription_type = (
406 None
407 if subscription_type_ref is None
408 else get_object_type(subscription_type_ref)
409 )
410
411 # Get the directives supported by Introspection, assuming empty-set if directives
412 # were not queried for.
413 directive_introspections = schema_introspection.get("directives")
414 directives = (
415 [
416 build_directive(directive_introspection)
417 for directive_introspection in directive_introspections
418 ]
419 if directive_introspections
420 else []
421 )
422
423 # Then produce and return a Schema with these types.
424 return GraphQLSchema(
425 query=query_type,
426 mutation=mutation_type,
427 subscription=subscription_type,
428 types=list(type_map.values()),
429 directives=directives,
430 description=schema_introspection.get("description"),
431 assume_valid=assume_valid,
432 )