Created
September 20, 2019 07:19
-
-
Save rob-blackbourn/fd83404b8a4cf51d5980b2e6a0edeb7d to your computer and use it in GitHub Desktop.
A Python GraphQL JSON type for graphqlql-core-next v1.1.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""GraphQL JSON type""" | |
import json | |
from typing import List, Mapping, Union, Any | |
from graphql.type import GraphQLScalarType | |
from graphql.language.ast import StringValueNode | |
from graphql.error import INVALID | |
JSONType = Union[List[Mapping[str, Any]], Mapping[str, Any]] | |
def _serialize_json(value: Any) -> JSONType: | |
if isinstance(value, (dict, list)): | |
return value | |
elif isinstance(value, str): | |
return json.loads(value) | |
else: | |
raise TypeError('Unable to serialize value') | |
def _coerce_json(value: Any) -> JSONType: | |
if isinstance(value, (dict, list)): | |
return value | |
raise TypeError('Unable to coerce type') | |
def _parse_json_literal(ast, _variables=None): | |
if isinstance(ast, StringValueNode): | |
result = json.loads(ast.value) | |
return result | |
return INVALID | |
# pylint: disable=invalid-name | |
GraphQLJson = GraphQLScalarType( | |
name="JSON", | |
description="The `JSON` scalar type", | |
serialize=_serialize_json, | |
parse_value=_coerce_json, | |
parse_literal=_parse_json_literal, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment