Superchain
Superchain is a high performant middleware chain.
Each chain-link calls the next one until the end of the chain was reached.
const chain = // add a middleware functionchain chain // add a final functionchain // run the chainconst result = chain // result is a promiseresult
The example above creates a chain with 3 items. Each item gets the same context object and calls the next chain-link. The final handler gets called as last one.
Not only callback functions
are supported. You deal with asynchronous code? Then use generators
or async functions
. We use co to execute generators.
Look at to their documentation to know more about generators.
const chain = // add a middleware functionchain chain // run the chainconst result = chainresult
Multiple arguments
Pass multiple arguments to run()
and each middleware gets all of it.
const chain = // add a middleware functionchain // run the chainchain
This context
Each middleware has the same this
context. An empty object is passed when chain starts. It could be used to transport data between middlewares. The final promise returns the this
context. Don't forget, arrow functions don't bind its own this
context. Use normal functions instead if you need access to it.
const chain = // add a middleware functionchain chain // run the chainchain
Final promise
The run()
method returns a promise. If you're using the callback style and do not call next()
the chain will stop and no promise will be called. In that case, you have to call finish()
which is the last argument. This is the only way to get notified when a callback has done its job. The finish
argument is not available in generators
or async functions
.
const chain = chain chain chain // run the chainchain
Calling finish()
is only necessary when you use the final promise.
Error handling
Whenever an error was thrown the promise gets rejected and the chain is canceled.
const chain = // add a middleware functionchain chain // run the chainconst result = chainresult
Conditions
Each middleware can have one condition function. The middleware gets called when the condition returns true otherwise it'll be skipped.
const chain = const condition = { return /^\/foo/} chain chain // run the chainconst result = chainresult
Bucket chain
A Bucketchain is a chain of buckets, each bucket contains one chain. Whenever a bucket chain starts, it runs the chain from first bucket and refers then to the second bucket. If any error occurs, the chain is canceld and the final promise gets rejected.
const bucketchain = const fooBucket = bucketchainconst barBucket = bucketchain fooBucket barBucket fooBucket const result = bucketchainresult
Next chain
chain chain chain
Debugging
Superchain has a simple debugging mode. Enable it by setting debug to true
const chain = chaindebug = true // or for a Bucketchan const chain = chaindebug = true