graphene/docs/execution/middleware.rst

69 lines
1.8 KiB
ReStructuredText
Raw Permalink Normal View History

2016-10-31 07:32:00 +03:00
Middleware
==========
You can use ``middleware`` to affect the evaluation of fields in your schema.
2017-12-08 17:58:03 +03:00
A middleware is any object or function that responds to ``resolve(next_middleware, *args)``.
2016-10-31 07:32:00 +03:00
Inside that method, it should either:
- Send ``resolve`` to the next middleware to continue the evaluation; or
- Return a value to end the evaluation early.
Resolve arguments
-----------------
Middlewares ``resolve`` is invoked with several arguments:
2019-04-09 21:29:40 +03:00
- ``next`` represents the execution chain. Call ``next`` to continue evaluation.
2016-10-31 07:32:00 +03:00
- ``root`` is the root value object passed throughout the query.
- ``info`` is the resolver info.
- ``args`` is the dict of arguments passed to the field.
2016-10-31 07:32:00 +03:00
Example
-------
This middleware only continues evaluation if the ``field_name`` is not ``'user'``
.. code:: python
class AuthorizationMiddleware(object):
def resolve(self, next, root, info, **args):
if info.field_name == 'user':
return None
2017-07-27 13:00:21 +03:00
return next(root, info, **args)
2016-10-31 07:32:00 +03:00
And then execute it with:
.. code:: python
result = schema.execute('THE QUERY', middleware=[AuthorizationMiddleware()])
2017-12-08 17:58:03 +03:00
Functional example
------------------
Middleware can also be defined as a function. Here we define a middleware that
logs the time it takes to resolve each field:
2017-12-08 17:58:03 +03:00
.. code:: python
from time import time as timer
def timing_middleware(next, root, info, **args):
start = timer()
return_value = next(root, info, **args)
duration = round((timer() - start) * 1000, 2)
parent_type_name = root._meta.name if root and hasattr(root, '_meta') else ''
logger.debug(f"{parent_type_name}.{info.field_name}: {duration} ms")
2017-12-08 17:58:03 +03:00
return return_value
And then execute it with:
.. code:: python
result = schema.execute('THE QUERY', middleware=[timing_middleware])