Skip to content

Commit c65d5a5

Browse files
authored
Updated docs reflecting static resolvers
(And a working example of is_type_of)
1 parent 69ad249 commit c65d5a5

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

docs/types/objecttypes.rst

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,12 @@ otherwise, the ``resolve_{field_name}`` within the ``ObjectType``.
5555
By default a resolver will take the ``args``, ``context`` and ``info``
5656
arguments.
5757

58+
NOTE: The class resolvers in a ``ObjectType`` are treated as ``staticmethod``s
59+
always, so the first argument in the resolver: ``self`` (or ``root``) doesn't
60+
need to be an actual instance of the ``ObjectType``. In the case this happens, please
61+
overwrite the ``is_type_of`` method.
62+
63+
5864
Quick example
5965
~~~~~~~~~~~~~
6066

@@ -90,6 +96,53 @@ A field could also specify a custom resolver outside the class:
9096
reverse = graphene.String(word=graphene.String(), resolver=reverse)
9197
9298
99+
Is Type Of
100+
----------
101+
102+
An ``ObjectType`` could be resolved within a object that is not an instance of this
103+
``ObjectType``. That means that the resolver of a ``Field`` could return any object.
104+
105+
Let's see an example:
106+
107+
.. code:: python
108+
import graphene
109+
110+
class Ship:
111+
def __init__(self, name):
112+
self.name = name
113+
114+
class ShipType(graphene.ObjectType):
115+
name = graphene.String(description="Ship name", required=True)
116+
117+
@resolve_only_args
118+
def resolve_name(self):
119+
# Here self will be the Ship instance returned in resolve_ship
120+
return self.name
121+
122+
class Query(graphene.ObjectType):
123+
ship = graphene.Field(ShipNode)
124+
125+
def resolve_ship(self, context, args, info):
126+
return Ship(name='xwing')
127+
128+
schema = graphene.Schema(query=Query)
129+
130+
131+
In this example, we are returning a ``Ship`` which is not an instance of ``ShipType``.
132+
If we execute a query on the ship, we would see this error:
133+
`"Expected value of type \"ShipType\" but got: instance."`
134+
135+
That's happening because GraphQL have no idea what type ``Ship`` is. For solving this,
136+
we only have to add a ``is_type_of`` method in ``ShipType``
137+
138+
.. code:: python
139+
140+
class ShipType(graphene.ObjectType):
141+
@classmethod
142+
def is_type_of(cls, root, context, info):
143+
return isinstance(root, (Ship, ShipType))
144+
145+
93146
Instances as data containers
94147
----------------------------
95148

0 commit comments

Comments
 (0)