ctx-compose
🌐 Universal middleware composing library based on koajs/koa-compose. Works with asynchronous and synchronous middleware on browsers, Node.js and React-Native.
Create your own middleware-based module!
Installation
npm install ctx-compose # or: yarn add ctx-compose
Usage
Import this module with:
// Module import; // CommonJS importconst compose composeSync = ; // Specific and lightweight importconst compose = ;const composeSync = ; // "Functional" wrapperconst compose = ;const composeSync = ;
And it is used like this:
const middleware = /* ... */;const context = {}; // it gets mutated along the middlewares // Asynchronous:await context; // Synchronous:context; console;
Asynchronous
The compose
function works exactly as Koa middlewares and supports asynchronous and synchronous middleware.
const compose = ;const Bluebird = ; { console; await ; console;} { await Bluebird; // wait 1000ms ctxvalue = ctxvalue + 1;} const context = value: 4 ;const middleware = log increaser;context ;
Synchronous
The composeSync
middleware works like this. It doesn't support async middleware:
const composeSync = ; { console; ; console;} { ctxvalue = ctxvalue + 1;} const context = value: 4 ;const middleware = log increaser;try context; console; catch err console;
Console output:
>>> 4<<< 5Value: 5
Functional mode
For convenience, you can use this wrapper that creates a shallow copy of the context
object before each layer of middleware (if needed) and return the final object as the result.
You can use a custom copy
function as the second argument of compose
. By default it uses:
{ return Object;}
Asynchronous
const compose = ;const Bluebird = ; { console; const nextCtx = await ; console; return nextCtx; // Explicit context return.} { await Bluebird; // wait 1000ms ctxvalue = ctxvalue + 1; return ctx; // Explicit context return.} const middleware = log increaser; value: 4 ;
const composeSync = ; { console; const nextCtx = ; console; return nextCtx; // Explicit context return.} { ctxvalue = ctxvalue + 1; return ctx; // Explicit context return.} const middleware = log increaser;try const context = value: 4 ; console; catch err console;
License
MIT