Debian Codegraph @

docs/usage/methods.rst

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