2.0.0 • Published 9 years ago
node-middlewares v2.0.0
Middlewares
Tiny and simple middlewares class for node and browserify.
Install
npm install node-middlewares
Usage
var Middlewares = require('node-middlewares');
var md = new Middlewares();
// add async middleware
md.use(function (ctx, next) {
doAsync(function (err, out) {
if (err) { return next(err); }
ctx.val++;
next();
});
});
// add sync middleware
md.use(function (ctx) {
ctx.val++;
});
// dispatch middlewares
md.dispatch(md); // dispatch with `md` context
md.dispatch({val: 40}, function (err, ctx) {
if (err) { return console.log('error', err.message); }
console.log('dispatched with', ctx.val)
}); // dispatch with 42 context
Extend constructors
var Module = function() {
// do something
};
util.inherits(Module, Middlewares);
var module = new Module();
module.use(middlewares);
module.dispatch(module);
If you want to operate middlewares
like array, you must create it manualy
in the constructor:
var Module = function() {
this.middlewares = [];
};
util.inherits(Module, Middlewares);
var module = new Module();
module.unshift(middleware);
module.splice(-1,0,middleware);
// etc
module.dispatch(module);
API
this.middlewares
Array of the used middlewares.
this.use([middleware|middlewares])
Method to add middleware or array of middlewares.
this.dispatch([ctx, callback])
Dispatch all used middlewares with given context and callback.
var host = new Middlewares();
host.use(middlewares);
host.dispatch(ctx, function(err, ctx) {
console.log('Yahooo!!!');
});
Middlewares
// async mw
var asyncMw = function (ctx, next) {
setTimeout(next, 0);
};
var syncMw = function (ctx) {
// do sync stuff
};
Errors
Middleware dispatching will be terminated and done(err)
callback will be invoked
with Error
from next(err)
.
License
MIT
2.0.0
9 years ago