-
-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathbuild_client_schema.py
446 lines (406 loc) · 17.2 KB
/
build_client_schema.py
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
"""GraphQL client schema creation"""
from __future__ import annotations
from itertools import chain
from typing import Callable, Collection, cast
from ..language import DirectiveLocation, parse_value
from ..pyutils import Undefined, inspect
from ..type import (
GraphQLArgument,
GraphQLDirective,
GraphQLEnumType,
GraphQLEnumValue,
GraphQLField,
GraphQLInputField,
GraphQLInputObjectType,
GraphQLInterfaceType,
GraphQLList,
GraphQLNamedType,
GraphQLNonNull,
GraphQLObjectType,
GraphQLScalarType,
GraphQLSchema,
GraphQLType,
GraphQLUnionType,
TypeKind,
assert_interface_type,
assert_nullable_type,
assert_object_type,
introspection_types,
is_input_type,
is_output_type,
specified_scalar_types,
)
from .get_introspection_query import (
IntrospectionDirective,
IntrospectionEnumType,
IntrospectionField,
IntrospectionInputObjectType,
IntrospectionInputValue,
IntrospectionInterfaceType,
IntrospectionObjectType,
IntrospectionQuery,
IntrospectionScalarType,
IntrospectionType,
IntrospectionTypeRef,
IntrospectionUnionType,
)
from .value_from_ast import value_from_ast
__all__ = ["build_client_schema"]
def build_client_schema(
introspection: IntrospectionQuery, assume_valid: bool = False
) -> GraphQLSchema:
"""Build a GraphQLSchema for use by client tools.
Given the result of a client running the introspection query, creates and returns
a GraphQLSchema instance which can be then used with all GraphQL-core 3 tools,
but cannot be used to execute a query, as introspection does not represent the
"resolver", "parse" or "serialize" functions or any other server-internal
mechanisms.
This function expects a complete introspection result. Don't forget to check the
"errors" field of a server response before calling this function.
"""
# Even though the `introspection` argument is typed, in most cases it's received
# as an untyped value from the server, so we will do an additional check here.
if not isinstance(introspection, dict) or not isinstance(
introspection.get("__schema"), dict
):
msg = (
"Invalid or incomplete introspection result. Ensure that you"
" are passing the 'data' attribute of an introspection response"
f" and no 'errors' were returned alongside: {inspect(introspection)}."
)
raise TypeError(msg)
# Get the schema from the introspection result.
schema_introspection = introspection["__schema"]
# Given a type reference in introspection, return the GraphQLType instance,
# preferring cached instances before building new instances.
def get_type(type_ref: IntrospectionTypeRef) -> GraphQLType:
kind = type_ref.get("kind")
if kind == TypeKind.LIST.name:
item_ref = type_ref.get("ofType")
if not item_ref:
msg = "Decorated type deeper than introspection query."
raise TypeError(msg)
item_ref = cast(IntrospectionTypeRef, item_ref)
return GraphQLList(get_type(item_ref))
if kind == TypeKind.NON_NULL.name:
nullable_ref = type_ref.get("ofType")
if not nullable_ref:
msg = "Decorated type deeper than introspection query."
raise TypeError(msg)
nullable_ref = cast(IntrospectionTypeRef, nullable_ref)
nullable_type = get_type(nullable_ref)
return GraphQLNonNull(assert_nullable_type(nullable_type))
type_ref = cast(IntrospectionType, type_ref)
return get_named_type(type_ref)
def get_named_type(type_ref: IntrospectionType) -> GraphQLNamedType:
type_name = type_ref.get("name")
if not type_name:
msg = f"Unknown type reference: {inspect(type_ref)}."
raise TypeError(msg)
type_ = type_map.get(type_name)
if not type_:
msg = (
f"Invalid or incomplete schema, unknown type: {type_name}."
" Ensure that a full introspection query is used in order"
" to build a client schema."
)
raise TypeError(msg)
return type_
def get_object_type(type_ref: IntrospectionObjectType) -> GraphQLObjectType:
return assert_object_type(get_type(type_ref))
def get_interface_type(
type_ref: IntrospectionInterfaceType,
) -> GraphQLInterfaceType:
return assert_interface_type(get_type(type_ref))
# Given a type's introspection result, construct the correct GraphQLType instance.
def build_type(type_: IntrospectionType) -> GraphQLNamedType:
if type_ and "name" in type_ and "kind" in type_:
builder = type_builders.get(type_["kind"])
if builder: # pragma: no cover else
return builder(type_)
msg = (
"Invalid or incomplete introspection result."
" Ensure that a full introspection query is used in order"
f" to build a client schema: {inspect(type_)}."
)
raise TypeError(msg)
def build_scalar_def(
scalar_introspection: IntrospectionScalarType,
) -> GraphQLScalarType:
name = scalar_introspection["name"]
try:
return cast(GraphQLScalarType, GraphQLScalarType.reserved_types[name])
except KeyError:
return GraphQLScalarType(
name=name,
description=scalar_introspection.get("description"),
specified_by_url=scalar_introspection.get("specifiedByURL"),
)
def build_implementations_list(
implementing_introspection: IntrospectionObjectType
| IntrospectionInterfaceType,
) -> list[GraphQLInterfaceType]:
maybe_interfaces = implementing_introspection.get("interfaces")
if maybe_interfaces is None:
# Temporary workaround until GraphQL ecosystem will fully support
# 'interfaces' on interface types
if implementing_introspection["kind"] == TypeKind.INTERFACE.name:
return []
msg = (
"Introspection result missing interfaces:"
f" {inspect(implementing_introspection)}."
)
raise TypeError(msg)
interfaces = cast(Collection[IntrospectionInterfaceType], maybe_interfaces)
return [get_interface_type(interface) for interface in interfaces]
def build_object_def(
object_introspection: IntrospectionObjectType,
) -> GraphQLObjectType:
name = object_introspection["name"]
try:
return cast(GraphQLObjectType, GraphQLObjectType.reserved_types[name])
except KeyError:
return GraphQLObjectType(
name=name,
description=object_introspection.get("description"),
interfaces=lambda: build_implementations_list(object_introspection),
fields=lambda: build_field_def_map(object_introspection),
)
def build_interface_def(
interface_introspection: IntrospectionInterfaceType,
) -> GraphQLInterfaceType:
return GraphQLInterfaceType(
name=interface_introspection["name"],
description=interface_introspection.get("description"),
interfaces=lambda: build_implementations_list(interface_introspection),
fields=lambda: build_field_def_map(interface_introspection),
)
def build_union_def(
union_introspection: IntrospectionUnionType,
) -> GraphQLUnionType:
maybe_possible_types = union_introspection.get("possibleTypes")
if maybe_possible_types is None:
msg = (
"Introspection result missing possibleTypes:"
f" {inspect(union_introspection)}."
)
raise TypeError(msg)
possible_types = cast(Collection[IntrospectionObjectType], maybe_possible_types)
return GraphQLUnionType(
name=union_introspection["name"],
description=union_introspection.get("description"),
types=lambda: [get_object_type(type_) for type_ in possible_types],
)
def build_enum_def(enum_introspection: IntrospectionEnumType) -> GraphQLEnumType:
if enum_introspection.get("enumValues") is None:
msg = (
"Introspection result missing enumValues:"
f" {inspect(enum_introspection)}."
)
raise TypeError(msg)
name = enum_introspection["name"]
try:
return cast(GraphQLEnumType, GraphQLEnumType.reserved_types[name])
except KeyError:
return GraphQLEnumType(
name=name,
description=enum_introspection.get("description"),
values={
value_introspect["name"]: GraphQLEnumValue(
value=value_introspect["name"],
description=value_introspect.get("description"),
deprecation_reason=value_introspect.get("deprecationReason"),
)
for value_introspect in enum_introspection["enumValues"]
},
)
def build_input_object_def(
input_object_introspection: IntrospectionInputObjectType,
) -> GraphQLInputObjectType:
if input_object_introspection.get("inputFields") is None:
msg = (
"Introspection result missing inputFields:"
f" {inspect(input_object_introspection)}."
)
raise TypeError(msg)
return GraphQLInputObjectType(
name=input_object_introspection["name"],
description=input_object_introspection.get("description"),
fields=lambda: build_input_value_def_map(
input_object_introspection["inputFields"]
),
)
type_builders: dict[str, Callable[[IntrospectionType], GraphQLNamedType]] = {
TypeKind.SCALAR.name: build_scalar_def, # type: ignore
TypeKind.OBJECT.name: build_object_def, # type: ignore
TypeKind.INTERFACE.name: build_interface_def, # type: ignore
TypeKind.UNION.name: build_union_def, # type: ignore
TypeKind.ENUM.name: build_enum_def, # type: ignore
TypeKind.INPUT_OBJECT.name: build_input_object_def, # type: ignore
}
def build_field_def_map(
type_introspection: IntrospectionObjectType | IntrospectionInterfaceType,
) -> dict[str, GraphQLField]:
if type_introspection.get("fields") is None:
msg = f"Introspection result missing fields: {type_introspection}."
raise TypeError(msg)
return {
field_introspection["name"]: build_field(field_introspection)
for field_introspection in type_introspection["fields"]
}
def build_field(field_introspection: IntrospectionField) -> GraphQLField:
type_introspection = cast(IntrospectionType, field_introspection["type"])
type_ = get_type(type_introspection)
if not is_output_type(type_):
msg = (
"Introspection must provide output type for fields,"
f" but received: {inspect(type_)}."
)
raise TypeError(msg)
args_introspection = field_introspection.get("args")
if args_introspection is None:
msg = (
"Introspection result missing field args:"
f" {inspect(field_introspection)}."
)
raise TypeError(msg)
return GraphQLField(
type_,
args=build_argument_def_map(args_introspection),
description=field_introspection.get("description"),
deprecation_reason=field_introspection.get("deprecationReason"),
)
def build_argument_def_map(
argument_value_introspections: Collection[IntrospectionInputValue],
) -> dict[str, GraphQLArgument]:
return {
argument_introspection["name"]: build_argument(argument_introspection)
for argument_introspection in argument_value_introspections
}
def build_argument(
argument_introspection: IntrospectionInputValue,
) -> GraphQLArgument:
type_introspection = cast(IntrospectionType, argument_introspection["type"])
type_ = get_type(type_introspection)
if not is_input_type(type_):
msg = (
"Introspection must provide input type for arguments,"
f" but received: {inspect(type_)}."
)
raise TypeError(msg)
default_value_introspection = argument_introspection.get("defaultValue")
default_value = (
Undefined
if default_value_introspection is None
else value_from_ast(parse_value(default_value_introspection), type_)
)
return GraphQLArgument(
type_,
default_value=default_value,
description=argument_introspection.get("description"),
deprecation_reason=argument_introspection.get("deprecationReason"),
)
def build_input_value_def_map(
input_value_introspections: Collection[IntrospectionInputValue],
) -> dict[str, GraphQLInputField]:
return {
input_value_introspection["name"]: build_input_value(
input_value_introspection
)
for input_value_introspection in input_value_introspections
}
def build_input_value(
input_value_introspection: IntrospectionInputValue,
) -> GraphQLInputField:
type_introspection = cast(IntrospectionType, input_value_introspection["type"])
type_ = get_type(type_introspection)
if not is_input_type(type_):
msg = (
"Introspection must provide input type for input fields,"
f" but received: {inspect(type_)}."
)
raise TypeError(msg)
default_value_introspection = input_value_introspection.get("defaultValue")
default_value = (
Undefined
if default_value_introspection is None
else value_from_ast(parse_value(default_value_introspection), type_)
)
return GraphQLInputField(
type_,
default_value=default_value,
description=input_value_introspection.get("description"),
deprecation_reason=input_value_introspection.get("deprecationReason"),
)
def build_directive(
directive_introspection: IntrospectionDirective,
) -> GraphQLDirective:
if directive_introspection.get("args") is None:
msg = (
"Introspection result missing directive args:"
f" {inspect(directive_introspection)}."
)
raise TypeError(msg)
if directive_introspection.get("locations") is None:
msg = (
"Introspection result missing directive locations:"
f" {inspect(directive_introspection)}."
)
raise TypeError(msg)
return GraphQLDirective(
name=directive_introspection["name"],
description=directive_introspection.get("description"),
is_repeatable=directive_introspection.get("isRepeatable", False),
locations=list(
cast(
Collection[DirectiveLocation],
directive_introspection.get("locations"),
)
),
args=build_argument_def_map(directive_introspection["args"]),
)
# Iterate through all types, getting the type definition for each.
type_map: dict[str, GraphQLNamedType] = {
type_introspection["name"]: build_type(type_introspection)
for type_introspection in schema_introspection["types"]
}
# Include standard types only if they are used.
for std_type_name, std_type in chain(
specified_scalar_types.items(), introspection_types.items()
):
if std_type_name in type_map:
type_map[std_type_name] = std_type
# Get the root Query, Mutation, and Subscription types.
query_type_ref = schema_introspection.get("queryType")
query_type = None if query_type_ref is None else get_object_type(query_type_ref)
mutation_type_ref = schema_introspection.get("mutationType")
mutation_type = (
None if mutation_type_ref is None else get_object_type(mutation_type_ref)
)
subscription_type_ref = schema_introspection.get("subscriptionType")
subscription_type = (
None
if subscription_type_ref is None
else get_object_type(subscription_type_ref)
)
# Get the directives supported by Introspection, assuming empty-set if directives
# were not queried for.
directive_introspections = schema_introspection.get("directives")
directives = (
[
build_directive(directive_introspection)
for directive_introspection in directive_introspections
]
if directive_introspections
else []
)
# Then produce and return a Schema with these types.
return GraphQLSchema(
query=query_type,
mutation=mutation_type,
subscription=subscription_type,
types=list(type_map.values()),
directives=directives,
description=schema_introspection.get("description"),
assume_valid=assume_valid,
)