@@ -3,7 +3,7 @@ Middleware
3
3
4
4
You can use ``middleware `` to affect the evaluation of fields in your schema.
5
5
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 ) ``.
7
7
8
8
Inside that method, it should either:
9
9
@@ -40,3 +40,32 @@ And then execute it with:
40
40
.. code :: python
41
41
42
42
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