Merge pull request #387 from hung-phan/master

Implement JSON type
This commit is contained in:
Syrus Akbary 2017-02-20 02:51:10 -08:00 committed by GitHub
commit 2044d29edb
2 changed files with 135 additions and 0 deletions

View File

@ -0,0 +1,39 @@
from __future__ import unicode_literals
from graphql.language.ast import (BooleanValue, FloatValue, IntValue,
StringValue, ListValue, ObjectValue)
from graphene.types.scalars import MIN_INT, MAX_INT
from .scalars import Scalar
class JSON(Scalar):
"""
The `JSON` scalar type represents JSON values as specified by
[ECMA-404](http://www.ecma-international.org/
publications/files/ECMA-ST/ECMA-404.pdf).
"""
@staticmethod
def identity(value):
return value
serialize = identity
parse_value = identity
@staticmethod
def parse_literal(ast):
if isinstance(ast, (StringValue, BooleanValue)):
return ast.value
elif isinstance(ast, IntValue):
num = int(ast.value)
if MIN_INT <= num <= MAX_INT:
return num
elif isinstance(ast, FloatValue):
return float(ast.value)
elif isinstance(ast, ListValue):
return [JSON.parse_literal(value) for value in ast.values]
elif isinstance(ast, ObjectValue):
return {field.name.value: JSON.parse_literal(field.value) for field in ast.fields}
else:
return None

View File

@ -0,0 +1,96 @@
from ..jsontype import JSON
from ..objecttype import ObjectType
from ..schema import Schema
class Query(ObjectType):
json = JSON(input=JSON())
def resolve_json(self, args, context, info):
input = args.get('input')
return input
schema = Schema(query=Query)
def test_json_query_variable():
for json_value in [
1,
1.1,
True,
'str',
[1, 2, 3],
[1.1, 2.2, 3.3],
[True, False],
['str1', 'str2'],
{
'key_a': 'a',
'key_b': 'b'
},
{
'int': 1,
'float': 1.1,
'boolean': True,
'string': 'str',
'int_list': [1, 2, 3],
'float_list': [1.1, 2.2, 3.3],
'boolean_list': [True, False],
'string_list': ['str1', 'str2'],
'nested_dict': {
'key_a': 'a',
'key_b': 'b'
}
},
None
]:
result = schema.execute(
'''query Test($json: JSON){ json(input: $json) }''',
variable_values={'json': json_value}
)
assert not result.errors
assert result.data == {
'json': json_value
}
def test_json_parse_literal_query():
result = schema.execute(
'''
query {
json(input: {
int: 1,
float: 1.1
boolean: true,
string: "str",
int_list: [1, 2, 3],
float_list: [1.1, 2.2, 3.3],
boolean_list: [true, false]
string_list: ["str1", "str2"],
nested_dict: {
key_a: "a",
key_b: "b"
},
empty_key: undefined
})
}
'''
)
assert not result.errors
assert result.data == {
'json': {
'int': 1,
'float': 1.1,
'boolean': True,
'string': 'str',
'int_list': [1, 2, 3],
'float_list': [1.1, 2.2, 3.3],
'boolean_list': [True, False],
'string_list': ['str1', 'str2'],
'nested_dict': {
'key_a': 'a',
'key_b': 'b'
},
'empty_key': None
}
}