|
| 1 | +import json |
| 2 | +import re |
| 3 | +import sys |
| 4 | +from ..compat import str_type |
| 5 | +from ..language import ast |
| 6 | +from ..type.definition import ( |
| 7 | + GraphQLEnumType, |
| 8 | + GraphQLInputObjectType, |
| 9 | + GraphQLList, |
| 10 | + GraphQLNonNull, |
| 11 | +) |
| 12 | +from ..type.scalars import GraphQLFloat |
| 13 | +from .is_nullish import is_nullish |
| 14 | + |
| 15 | + |
| 16 | +def ast_from_value(value, type=None): |
| 17 | + if isinstance(type, GraphQLNonNull): |
| 18 | + return ast_from_value(value, type.of_type) |
| 19 | + |
| 20 | + if is_nullish(value): |
| 21 | + return None |
| 22 | + |
| 23 | + if isinstance(value, list): |
| 24 | + item_type = type.of_type if isinstance(type, GraphQLList) else None |
| 25 | + return ast.ListValue([ast_from_value(item, item_type) for item in value]) |
| 26 | + |
| 27 | + elif isinstance(type, GraphQLList): |
| 28 | + return ast_from_value(value, type.of_type) |
| 29 | + |
| 30 | + if isinstance(value, bool): |
| 31 | + return ast.BooleanValue(value) |
| 32 | + |
| 33 | + if isinstance(value, (int, float)): |
| 34 | + string_num = str(value) |
| 35 | + int_value = int(value) |
| 36 | + is_int_value = string_num.isdigit() |
| 37 | + |
| 38 | + if is_int_value or (int_value == value and value < sys.maxsize): |
| 39 | + if type == GraphQLFloat: |
| 40 | + return ast.FloatValue(str(float(value))) |
| 41 | + |
| 42 | + return ast.IntValue(str(int(value))) |
| 43 | + |
| 44 | + return ast.FloatValue(string_num) |
| 45 | + |
| 46 | + if isinstance(value, str_type): |
| 47 | + if isinstance(type, GraphQLEnumType) and re.match(r'^[_a-zA-Z][_a-zA-Z0-9]*$', value): |
| 48 | + return ast.EnumValue(value) |
| 49 | + |
| 50 | + return ast.StringValue(json.dumps(value)[1:-1]) |
| 51 | + |
| 52 | + assert isinstance(value, dict) |
| 53 | + |
| 54 | + fields = [] |
| 55 | + is_graph_ql_input_object_type = isinstance(type, GraphQLInputObjectType) |
| 56 | + |
| 57 | + for field_name, field_value in value.items(): |
| 58 | + field_type = None |
| 59 | + if is_graph_ql_input_object_type: |
| 60 | + field_def = type.get_fields().get(field_name) |
| 61 | + field_type = field_def and field_def.type |
| 62 | + |
| 63 | + field_value = ast_from_value(field_value, field_type) |
| 64 | + if field_value: |
| 65 | + fields.append(ast.ObjectField( |
| 66 | + ast.Name(field_name), |
| 67 | + field_value |
| 68 | + )) |
| 69 | + |
| 70 | + return ast.ObjectValue(fields) |
0 commit comments