|
| 1 | +Using resolver methods |
| 2 | +---------------------- |
| 3 | + |
| 4 | +Above we have attached resolver functions to the schema only. However, it is |
| 5 | +also possible to define resolver methods on the resolved objects, starting with |
| 6 | +the ``root_value`` object that you can pass to the :func:`graphql.graphql` |
| 7 | +function when executing a query. |
| 8 | + |
| 9 | +In our case, we could create a ``Root`` class with three methods as root |
| 10 | +resolvers, like so:: |
| 11 | + |
| 12 | + class Root(): |
| 13 | + """The root resolvers""" |
| 14 | + |
| 15 | + def hero(self, info, episode): |
| 16 | + return luke if episode == 5 else artoo |
| 17 | + |
| 18 | + def human(self, info, id): |
| 19 | + return human_data.get(id) |
| 20 | + |
| 21 | + def droid(self, info, id): |
| 22 | + return droid_data.get(id) |
| 23 | + |
| 24 | + |
| 25 | +Since we haven't defined synchronous methods only, we will use the |
| 26 | +:func:`graphql.graphql_sync` function to execute a query, passing |
| 27 | +a ``Root()`` object as the ``root_value``:: |
| 28 | + |
| 29 | + from graphql import graphql_sync |
| 30 | + |
| 31 | + result = graphql_sync(schema, """ |
| 32 | + { |
| 33 | + droid(id: "2001") { |
| 34 | + name |
| 35 | + primaryFunction |
| 36 | + } |
| 37 | + } |
| 38 | + """, Root()) |
| 39 | + print(result) |
| 40 | + |
| 41 | +Even if we haven't attached a resolver to the ``hero`` field as we did above, |
| 42 | +this would now still resolve and give the following output:: |
| 43 | + |
| 44 | + ExecutionResult( |
| 45 | + data={'droid': {'name': 'R2-D2', 'primaryFunction': 'Astromech'}}, |
| 46 | + errors=None) |
| 47 | + |
| 48 | +Of course you can also define asynchronous methods as resolvers, and execute |
| 49 | +queries asynchronously with :func:`graphql.graphql`. |
| 50 | + |
| 51 | +In a similar vein, you can also attach resolvers as methods to the resolved |
| 52 | +objects on deeper levels than the root of the query. In that case, instead |
| 53 | +of resolving to dictionaries with keys for all the fields, as we did above, |
| 54 | +you would resolve to objects with attributes for all the fields. For instance, |
| 55 | +you would define a class ``Human`` with a method :meth:`friends` for resolving |
| 56 | +the friends of a human. You can also make use of inheritance in this case. |
| 57 | +The ``Human`` class and a ``Droid`` class could inherit from a ``Character`` |
| 58 | +class and use its methods as resolvers for common fields. |
0 commit comments