Merge pull request #362 from Globegitter/node-parent-type

Node parent type
This commit is contained in:
Syrus Akbary 2016-11-14 19:13:36 -08:00 committed by GitHub
commit e26bbdd937
2 changed files with 47 additions and 7 deletions

View File

@ -35,17 +35,19 @@ def get_default_connection(cls):
class GlobalID(Field):
def __init__(self, node=None, required=True, *args, **kwargs):
def __init__(self, node=None, parent_type=None, required=True, *args, **kwargs):
super(GlobalID, self).__init__(ID, required=required, *args, **kwargs)
self.node = node or Node
self.parent_type_name = parent_type._meta.name if parent_type else None
@staticmethod
def id_resolver(parent_resolver, node, root, args, context, info):
id = parent_resolver(root, args, context, info)
return node.to_global_id(info.parent_type.name, id) # root._meta.name
def id_resolver(parent_resolver, node, root, args, context, info, parent_type_name=None):
type_id = parent_resolver(root, args, context, info)
parent_type_name = parent_type_name or info.parent_type.name
return node.to_global_id(parent_type_name, type_id) # root._meta.name
def get_resolver(self, parent_resolver):
return partial(self.id_resolver, parent_resolver, self.node)
return partial(self.id_resolver, parent_resolver, self.node, parent_type_name=self.parent_type_name)
class NodeMeta(InterfaceMeta):

View File

@ -1,6 +1,8 @@
from ..node import Node, GlobalID
from graphql_relay import to_global_id
from ...types import NonNull, ID
from ..node import Node, GlobalID
from ...types import NonNull, ID, ObjectType, String
from ...types.definitions import GrapheneObjectType
class CustomNode(Node):
@ -9,6 +11,26 @@ class CustomNode(Node):
name = 'Node'
class User(ObjectType):
class Meta:
interfaces = [CustomNode]
name = String()
class Info(object):
def __init__(self, parent_type):
self.parent_type = GrapheneObjectType(
graphene_type=parent_type,
name=parent_type._meta.name,
description=parent_type._meta.description,
fields=None,
is_type_of=parent_type.is_type_of,
interfaces=None
)
def test_global_id_defaults_to_required_and_node():
gid = GlobalID()
assert isinstance(gid.type, NonNull)
@ -20,3 +42,19 @@ def test_global_id_allows_overriding_of_node_and_required():
gid = GlobalID(node=CustomNode, required=False)
assert gid.type == ID
assert gid.node == CustomNode
def test_global_id_defaults_to_info_parent_type():
my_id = '1'
gid = GlobalID()
id_resolver = gid.get_resolver(lambda *_: my_id)
my_global_id = id_resolver(None, None, None, Info(User))
assert my_global_id == to_global_id(User._meta.name, my_id)
def test_global_id_allows_setting_customer_parent_type():
my_id = '1'
gid = GlobalID(parent_type=User)
id_resolver = gid.get_resolver(lambda *_: my_id)
my_global_id = id_resolver(None, None, None, None)
assert my_global_id == to_global_id(User._meta.name, my_id)