Implementing GraphQL Middleware
Middleware provides a convenient way to filter your GraphQL query or mutation. For example, it can be used to authenticate your user or check certain capabilities. Middleware refers to standalone classes which can be assigned to multiple resolvers. Middleware can be tested individually and reused throughout a plugin or the whole site.
For example, middleware can be used to check whether the user is authenticated (calling require_login
) and interrupt the request if the user is not. If the user is authenticated, the middleware will allow the request to proceed further to the next middleware or to the resolver.
You can envision middleware as a series of layers around our resolvers which must be passed through. Each layer can examine the request, manipulate it, and even reject it. The same is true for the outgoing result, which has to pass through middleware (defined as after middleware) where the result can be examined or manipulated.