GraphQL Chain
Create GraphQL middleware that resembles how Express middleware works.
Install
yarn add graphql-chain
How to use
Step 1
Create middleware
const validationMiddleware: MiddlewareResolver = next parent args context info if argsnamelength > 10 throw "too long"; return ;;
It has access to all the regular parameters a resolver gets plus a next
parameter at the beginning which you call and return to call the next middleware or resolver.
You don't always have to call the next middleware or resolver though. This can be helpful if you want create a caching middleware:
const cachingMiddleware: MiddlewareResolver = async { const data = await redis; if data // found data in the cache, so return early console; return data; // did not find data, so call the next middleware console; const result = await ; // set cache for next call await redis; return result;};
You can also change the value of the arguments and then use them later
const getUserMiddleware: MiddlewareResolver = async { if // you can add properties to context that you can use later contextuser = await ; return ;};
So you can then have a middleware that checks the user
const authorizationMiddleware: MiddlewareResolver = { if !contextuser || !contextuseradmin throw "not authorized"; return ;};
Step 2
Chain as many middlewares together as you like
; const helloMiddleware = ;
Step 3
Wrap the resolver you want the middleware to run on
const resolvers: IResolvers = Query: hello: ;
The execution sequence will be getUserMiddleware
-> authorizationMiddleware
-> validationMiddleware
-> hello
Checkout the examples
directory for complete examples