-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathbuild_ast_schema.py
More file actions
361 lines (298 loc) · 11 KB
/
build_ast_schema.py
File metadata and controls
361 lines (298 loc) · 11 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
from ..execution.values import get_argument_values
from ..language import ast
from ..pyutils.ordereddict import OrderedDict
from ..type import (
GraphQLArgument,
GraphQLBoolean,
GraphQLDeferDirective,
GraphQLDeprecatedDirective,
GraphQLDirective,
GraphQLEnumType,
GraphQLEnumValue,
GraphQLField,
GraphQLFloat,
GraphQLID,
GraphQLIncludeDirective,
GraphQLInputObjectField,
GraphQLInputObjectType,
GraphQLInt,
GraphQLInterfaceType,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLScalarType,
GraphQLSchema,
GraphQLSkipDirective,
GraphQLString,
GraphQLUnionType,
)
from ..type.introspection import (
__Directive,
__DirectiveLocation,
__EnumValue,
__Field,
__InputValue,
__Schema,
__Type,
__TypeKind,
)
from ..utils.value_from_ast import value_from_ast
def _build_wrapped_type(inner_type, input_type_ast):
if isinstance(input_type_ast, ast.ListType):
return GraphQLList(_build_wrapped_type(inner_type, input_type_ast.type))
if isinstance(input_type_ast, ast.NonNullType):
return GraphQLNonNull(_build_wrapped_type(inner_type, input_type_ast.type))
return inner_type
def _get_inner_type_name(type_ast):
if isinstance(type_ast, (ast.ListType, ast.NonNullType)):
return _get_inner_type_name(type_ast.type)
return type_ast.name.value
def _get_named_type_ast(type_ast):
named_type = type_ast
while isinstance(named_type, (ast.ListType, ast.NonNullType)):
named_type = named_type.type
return named_type
def _false(*_):
return False
def _none(*_):
return None
def build_ast_schema(document):
assert isinstance(document, ast.Document), "must pass in Document ast."
schema_def = None
type_asts = (
ast.ScalarTypeDefinition,
ast.ObjectTypeDefinition,
ast.InterfaceTypeDefinition,
ast.EnumTypeDefinition,
ast.UnionTypeDefinition,
ast.InputObjectTypeDefinition,
)
type_defs = []
directive_defs = []
for d in document.definitions:
if isinstance(d, ast.SchemaDefinition):
if schema_def:
raise Exception("Must provide only one schema definition.")
schema_def = d
if isinstance(d, type_asts):
type_defs.append(d)
elif isinstance(d, ast.DirectiveDefinition):
directive_defs.append(d)
if not schema_def:
raise Exception("Must provide a schema definition.")
query_type_name = None
mutation_type_name = None
subscription_type_name = None
for operation_type in schema_def.operation_types:
type_name = operation_type.type.name.value
if operation_type.operation == "query":
if query_type_name:
raise Exception("Must provide only one query type in schema.")
query_type_name = type_name
elif operation_type.operation == "mutation":
if mutation_type_name:
raise Exception("Must provide only one mutation type in schema.")
mutation_type_name = type_name
elif operation_type.operation == "subscription":
if subscription_type_name:
raise Exception("Must provide only one subscription type in schema.")
subscription_type_name = type_name
if not query_type_name:
raise Exception("Must provide schema definition with query type.")
ast_map = {d.name.value: d for d in type_defs}
if query_type_name not in ast_map:
raise Exception(
'Specified query type "{}" not found in document.'.format(query_type_name)
)
if mutation_type_name and mutation_type_name not in ast_map:
raise Exception(
'Specified mutation type "{}" not found in document.'.format(
mutation_type_name
)
)
if subscription_type_name and subscription_type_name not in ast_map:
raise Exception(
'Specified subscription type "{}" not found in document.'.format(
subscription_type_name
)
)
inner_type_map = OrderedDict(
[
("String", GraphQLString),
("Int", GraphQLInt),
("Float", GraphQLFloat),
("Boolean", GraphQLBoolean),
("ID", GraphQLID),
("__Schema", __Schema),
("__Directive", __Directive),
("__DirectiveLocation", __DirectiveLocation),
("__Type", __Type),
("__Field", __Field),
("__InputValue", __InputValue),
("__EnumValue", __EnumValue),
("__TypeKind", __TypeKind),
]
)
def get_directive(directive_ast):
return GraphQLDirective(
name=directive_ast.name.value,
locations=[node.value for node in directive_ast.locations],
args=make_input_values(directive_ast.arguments, GraphQLArgument),
)
def get_object_type(type_ast):
type = type_def_named(type_ast.name.value)
assert isinstance(type, GraphQLObjectType), "AST must provide object type"
return type
def produce_type_def(type_ast):
type_name = _get_named_type_ast(type_ast).name.value
type_def = type_def_named(type_name)
return _build_wrapped_type(type_def, type_ast)
def type_def_named(type_name):
if type_name in inner_type_map:
return inner_type_map[type_name]
if type_name not in ast_map:
raise Exception('Type "{}" not found in document'.format(type_name))
inner_type_def = make_schema_def(ast_map[type_name])
if not inner_type_def:
raise Exception('Nothing constructed for "{}".'.format(type_name))
inner_type_map[type_name] = inner_type_def
return inner_type_def
def make_schema_def(definition):
if not definition:
raise Exception("def must be defined.")
handler = _schema_def_handlers.get(type(definition))
if not handler:
raise Exception(
'Type kind "{}" not supported.'.format(type(definition).__name__)
)
return handler(definition)
def make_type_def(definition):
return GraphQLObjectType(
name=definition.name.value,
fields=lambda: make_field_def_map(definition),
interfaces=make_implemented_interfaces(definition),
)
def make_field_def_map(definition):
return OrderedDict(
(
f.name.value,
GraphQLField(
type=produce_type_def(f.type),
args=make_input_values(f.arguments, GraphQLArgument),
deprecation_reason=get_deprecation_reason(f.directives),
),
)
for f in definition.fields
)
def make_implemented_interfaces(definition):
return [produce_type_def(i) for i in definition.interfaces]
def make_input_values(values, cls):
return OrderedDict(
(
value.name.value,
cls(
type=produce_type_def(value.type),
default_value=value_from_ast(
value.default_value, produce_type_def(value.type)
),
),
)
for value in values
)
def make_interface_def(definition):
return GraphQLInterfaceType(
name=definition.name.value,
resolve_type=_none,
fields=lambda: make_field_def_map(definition),
)
def make_enum_def(definition):
values = OrderedDict(
(
v.name.value,
GraphQLEnumValue(
deprecation_reason=get_deprecation_reason(v.directives)
),
)
for v in definition.values
)
return GraphQLEnumType(name=definition.name.value, values=values)
def make_union_def(definition):
return GraphQLUnionType(
name=definition.name.value,
resolve_type=_none,
types=[produce_type_def(t) for t in definition.types],
)
def make_scalar_def(definition):
return GraphQLScalarType(
name=definition.name.value,
serialize=_none,
# Validation calls the parse functions to determine if a literal value is correct.
# Returning none, however would cause the scalar to fail validation. Returning false,
# will cause them to pass.
parse_literal=_false,
parse_value=_false,
)
def make_input_object_def(definition):
return GraphQLInputObjectType(
name=definition.name.value,
fields=lambda: make_input_values(
definition.fields, GraphQLInputObjectField
),
)
_schema_def_handlers = {
ast.ObjectTypeDefinition: make_type_def,
ast.InterfaceTypeDefinition: make_interface_def,
ast.EnumTypeDefinition: make_enum_def,
ast.UnionTypeDefinition: make_union_def,
ast.ScalarTypeDefinition: make_scalar_def,
ast.InputObjectTypeDefinition: make_input_object_def,
}
types = [type_def_named(definition.name.value) for definition in type_defs]
directives = [get_directive(d) for d in directive_defs]
# If specified directive were not explicitly declared, add them.
find_skip_directive = (
directive.name for directive in directives if directive.name == "skip"
)
find_include_directive = (
directive.name for directive in directives if directive.name == "include"
)
find_deprecated_directive = (
directive.name for directive in directives if directive.name == "deprecated"
)
find_defer_directive = (
directive.name for directive in directives if directive.name == "defer"
)
if not next(find_skip_directive, None):
directives.append(GraphQLSkipDirective)
if not next(find_include_directive, None):
directives.append(GraphQLIncludeDirective)
if not next(find_deprecated_directive, None):
directives.append(GraphQLDeprecatedDirective)
if not next(find_defer_directive, None):
directives.append(GraphQLDeferDirective)
schema_kwargs = {"query": get_object_type(ast_map[query_type_name])}
if mutation_type_name:
schema_kwargs["mutation"] = get_object_type(ast_map[mutation_type_name])
if subscription_type_name:
schema_kwargs["subscription"] = get_object_type(ast_map[subscription_type_name])
if directive_defs:
schema_kwargs["directives"] = directives
if types:
schema_kwargs["types"] = types
return GraphQLSchema(**schema_kwargs)
def get_deprecation_reason(directives):
deprecated_ast = next(
(
directive
for directive in directives
if directive.name.value == GraphQLDeprecatedDirective.name
),
None,
)
if deprecated_ast:
args = get_argument_values(
GraphQLDeprecatedDirective.args, deprecated_ast.arguments
)
return args["reason"]
else:
return None