Skip to content

Commit 92f6a49

Browse files
authored
Merge pull request #622 from jkimbo/docs-middleware-update
[Docs] Functional middleware example
2 parents 6c92e25 + 502597c commit 92f6a49

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

docs/execution/middleware.rst

+30-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ Middleware
33

44
You can use ``middleware`` to affect the evaluation of fields in your schema.
55

6-
A middleware is any object that responds to ``resolve(*args, next_middleware)``.
6+
A middleware is any object or function that responds to ``resolve(next_middleware, *args)``.
77

88
Inside that method, it should either:
99

@@ -40,3 +40,32 @@ And then execute it with:
4040
.. code:: python
4141
4242
result = schema.execute('THE QUERY', middleware=[AuthorizationMiddleware()])
43+
44+
45+
Functional example
46+
------------------
47+
48+
Middleware can also be defined as a function. Here we define a middleware that
49+
logs the time it takes to resolve each field
50+
51+
.. code:: python
52+
53+
from time import time as timer
54+
55+
def timing_middleware(next, root, info, **args):
56+
start = timer()
57+
return_value = next(root, info, **args)
58+
duration = timer() - start
59+
logger.debug("{parent_type}.{field_name}: {duration} ms".format(
60+
parent_type=root._meta.name if root else '',
61+
field_name=info.field_name,
62+
duration=round(duration * 1000, 2)
63+
))
64+
return return_value
65+
66+
67+
And then execute it with:
68+
69+
.. code:: python
70+
71+
result = schema.execute('THE QUERY', middleware=[timing_middleware])

0 commit comments

Comments
 (0)