Refactor converter

This commit is contained in:
Patrick Arminio 2017-06-26 11:36:48 +01:00
parent c3899248af
commit d10895d9ce

View File

@ -24,49 +24,45 @@ def convert_serializer_to_input_type(serializer_class):
@singledispatch
def convert_serializer_field(field):
def get_graphene_type_from_serializer_field(field):
raise ImproperlyConfigured(
"Don't know how to convert the serializer field %s (%s) "
"to Graphene type" % (field, field.__class__)
)
def required_if_input_and_required(func):
def convert_serializer_field(field, is_input=True):
"""
Marks the field as required if we are creating an input type
Converts a django rest frameworks field to a graphql field
and marks the field as required if we are creating an input type
and the field itself is required
"""
def wrap(field, is_input=True):
graphql_type = func(field)
# TODO: sub types? kwargs
graphql_type = get_graphene_type_from_serializer_field(field)
return graphql_type(
description=field.help_text, required=is_input and field.required
)
return wrap
@convert_serializer_field.register(serializers.Field)
@required_if_input_and_required
@get_graphene_type_from_serializer_field.register(serializers.Field)
def convert_serializer_field_to_string(field):
return graphene.String
@convert_serializer_field.register(serializers.IntegerField)
@required_if_input_and_required
@get_graphene_type_from_serializer_field.register(serializers.IntegerField)
def convert_serializer_field_to_int(field):
return graphene.Int
@convert_serializer_field.register(serializers.BooleanField)
@required_if_input_and_required
@get_graphene_type_from_serializer_field.register(serializers.BooleanField)
def convert_serializer_field_to_bool(field):
return graphene.Boolean
@convert_serializer_field.register(serializers.FloatField)
@convert_serializer_field.register(serializers.DecimalField)
@required_if_input_and_required
@get_graphene_type_from_serializer_field.register(serializers.FloatField)
@get_graphene_type_from_serializer_field.register(serializers.DecimalField)
def convert_serializer_field_to_float(field):
return graphene.Float