Improved scalar implementation thinking immutable

This commit is contained in:
Syrus Akbary 2016-06-06 00:48:43 -07:00
parent 77ec170dd5
commit 251d7106e2
2 changed files with 9 additions and 50 deletions

View File

@ -6,45 +6,7 @@ from .proxy import TypeProxy
class GrapheneScalarType(GrapheneGraphQLType, GraphQLScalarType):
def __init__(self, *args, **kwargs):
GrapheneGraphQLType.__init__(self, *args, **kwargs)
@staticmethod
def default_parse(value):
return None
def setup(self):
serialize = getattr(self.graphene_type, 'serialize', None)
parse_value = getattr(self.graphene_type, 'parse_value', None)
parse_literal = getattr(self.graphene_type, 'parse_literal', None)
assert callable(serialize), (
'{} must provide "serialize" function. If this custom Scalar is '
'also used as an input type, ensure "parse_value" and "parse_literal" '
'functions are also provided.'
).format(self)
if parse_value is not None or parse_literal is not None:
assert callable(parse_value) and callable(parse_literal), (
'{} must provide both "parse_value" and "parse_literal" functions.'.format(self)
)
self._serialize = serialize
self._parse_value = parse_value
self._parse_literal = parse_literal
@property
def serialize(self):
return self.graphene_type.serialize
@property
def parse_value(self):
return getattr(self.graphene_type, 'parse_value', self.default_parse)
@property
def parse_literal(self):
return getattr(self.graphene_type, 'parse_literal', self.default_parse)
pass
class ScalarTypeMeta(ClassTypeMeta):
@ -59,19 +21,21 @@ class ScalarTypeMeta(ClassTypeMeta):
)
def construct_graphql_type(cls, bases):
pass
def construct(cls, *args, **kwargs):
constructed = super(ScalarTypeMeta, cls).construct(*args, **kwargs)
if not cls._meta.graphql_type and not cls._meta.abstract:
cls._meta.graphql_type = GrapheneScalarType(
graphene_type=cls,
name=cls._meta.name or cls.__name__,
description=cls._meta.description,
# For passing the assertion in GraphQLScalarType
serialize=lambda: None
serialize=getattr(cls, 'serialize', None),
parse_value=getattr(cls, 'parse_value', None),
parse_literal=getattr(cls, 'parse_literal', None),
)
def construct(cls, *args, **kwargs):
constructed = super(ScalarTypeMeta, cls).construct(*args, **kwargs)
if isinstance(cls._meta.graphql_type, GrapheneScalarType):
cls._meta.graphql_type.setup()
return constructed

View File

@ -48,8 +48,3 @@ def test_custom_scalar_empty():
pass
assert """DatetimeScalar must provide "serialize" function.""" in str(excinfo.value)
def test_custom_scalar():
graphql_type = DatetimeScalar._meta.graphql_type
assert graphql_type.serialize == DatetimeScalar.serialize