Added Plugins structure. Added option in schema for auto camel case or not.

This commit is contained in:
Syrus Akbary 2015-12-06 02:35:17 -08:00
parent ec3f292593
commit 12e4e2c006
5 changed files with 50 additions and 2 deletions

View File

@ -12,6 +12,7 @@ from graphene import signals
from .classtypes.base import ClassType
from .types.base import BaseType
from ..plugins import Plugin, CamelCase
class GraphQLSchema(_GraphQLSchema):
@ -25,7 +26,7 @@ class Schema(object):
_executor = None
def __init__(self, query=None, mutation=None, subscription=None,
name='Schema', executor=None):
name='Schema', executor=None, plugins=None, auto_camelcase=True):
self._types_names = {}
self._types = {}
self.mutation = mutation
@ -33,12 +34,25 @@ class Schema(object):
self.subscription = subscription
self.name = name
self.executor = executor
self.plugins = []
plugins = plugins or []
if auto_camelcase:
plugins.append(CamelCase())
for plugin in plugins:
self.add_plugin(plugin)
signals.init_schema.send(self)
def __repr__(self):
return '<Schema: %s (%s)>' % (str(self.name), hash(self))
def add_plugin(self, plugin):
assert isinstance(plugin, Plugin), 'A plugin need to subclass graphene.Plugin and be instantiated'
plugin.contribute_to_schema(self)
self.plugins.append(plugin)
def get_internal_type(self, objecttype):
for plugin in self.plugins:
objecttype = plugin.transform_type(objecttype)
return objecttype.internal_type(self)
def T(self, object_type):

View File

@ -140,7 +140,7 @@ class GroupNamedType(BaseType):
self.types = types
def get_named_type(self, schema, type):
name = type.name or to_camel_case(type.attname)
name = type.name or type.attname
return name, schema.T(type)
def internal_type(self, schema):

View File

@ -0,0 +1,6 @@
from .base import Plugin
from .camel_case import CamelCase
__all__ = [
'Plugin', 'CamelCase'
]

6
graphene/plugins/base.py Normal file
View File

@ -0,0 +1,6 @@
class Plugin(object):
def contribute_to_schema(self, schema):
self.schema = schema
def transform_type(self, objecttype):
return objecttype

View File

@ -0,0 +1,22 @@
from .base import Plugin
from ..core.types.base import GroupNamedType
from ..utils import memoize, to_camel_case
def camelcase_named_type(schema, type):
name = type.name or to_camel_case(type.attname)
return name, schema.T(type)
class CamelCase(Plugin):
@memoize
def transform_group(self, _type):
new_type = _type.__class__(*_type.types)
setattr(new_type, 'get_named_type', camelcase_named_type)
return new_type
def transform_type(self, _type):
if isinstance(_type, GroupNamedType):
return self.transform_group(_type)
return _type