Middlewarify
Apply the middleware pattern, easy. You can add two types of middleware, a single queue type using the keyword use()
or a Before/After type using before()
and after()
hooks.
Install
npm install middlewarify --save
Quick Start
Quick Start Example
Creating a middleware:
var midd = require('middlewarify');
var tasks = module.exports = {};
function createTask(done) {
console.log('createTask Final Fn to be invoked');
done();
}
midd.make(tasks, 'create', createTask);
...Add middleware
var tasks = require('./tasks');
tasks.create.use(function(next){
console.log('middleware 1');
next();
});
tasks.create.use(function(next){
console.log('middleware 2');
next();
});
... Invoke all the middleware
tasks.create();
Invoking the middleware will return an object with a done
property which you can use to setup your callbacks:
tasks.create().done(function(err) {
});
Using the Before / After Middleware type
var midd = require('middlewarify');
var tasks = module.exports = {};
function createTask(done) {
console.log('Invoked Second');
done(null);
};
midd.make(tasks, 'create', createTask, {beforeAfter: true});
tasks.create.before(function(next) {
console.log('Invoked First');
next();
});
tasks.create.after(function(next) {
console.log('Invoked Third and last');
next();
});
tasks.create().done(function(err){
});
Middlewarify Methods
make(object, property, optMainCallback, optOptions)
The middlewarify.make()
method will apply the middleware pattern to an Object's property, this property will be called the Middleware Container.
var crud = {};
middlewarify.make(crud, 'create');
This example has created the Middleware Container create
in the object crud
. create.crud
is a function that will invoke all the middleware.
You can add a third argument, the optMainCallback
, this is the main payload of your middleware. optOptions
is one more argument you can pass to Middlewarify to define behavior. Both optOptions
and optMainCallback
are optional and can be interswitched, i.e. you can pass options as a third argument, read on for examples and what are the available options.
make() Options
make()
accepts the following options:
throwErrors
type: Boolean, default: true
If set to false all thrown errors will be suppressed and available only through the .done()
method.beforeAfter
type: Boolean, default: false
If set to true the Before/After hooks will be used instead of the single queue use
hook, which is the default, view the example displayed above.
throwErrors
Example
var crud = {};
middlewarify.make(crud, 'create', {throwErrors: false});
crud.create.use(function(){
throw new Error('an error');
});
crud.create().done(function(err) {
err.message === 'an error';
});
The use(fn) Method
The Middleware Container by default exposes a use
method so you can add any number of middleware. use()
accepts any number of parameters as long they are of type Function or Arrays of Functions. When the Before/After flag is enabled use
is no longer there and instead you get before
and after
methods to hook your middleware. All three hook types accept the same argument types and patterns as described bellow.
var crud = {};
middlewarify.make(crud, 'create', fnFinal);
crud.create.use([fn1, fn2], fn3);
crud.create.use(fn4);
In the above example we added 4 middleware before the final method fnFinal
will be invoked. A FIFO queue is implemented so the order of execution will be:
fn1()
fn2()
fn3()
fn4()
fnFinal()
Middleware Arguments
All middleware gets invoked with a callback so it can pass control to the next middleware.
following up on the previous examples:
crud.create.use(function(next) {
next();
});
The first argument of the next()
callback is the error indicator, any truthy value passed will be considered an error and stop executing the middleware chain right there and then.
crud.create.use(function(next) {
next('an error occured');
});
If the Middleware Container is invoked with arguments, these arguments will be passed to all middleware and the callback function next
will always be the last argument. Read the next section "Invoking the Middleware" for more.
Invoking the Middleware
The Middleware Container is nothing but a function that accepts any number of arguments.
Any argument passed to the Middleware Container will also be passed to all middleware.
var crud = {};
middlewarify.make(crud, 'create');
crud.create({a: 1, b:2}, 'bar');
Arguments middleware will get:
crud.create.use(function(arg1, arg2, next) {
arg1 === {a:1, b:2};
arg2 === 'bar';
next();
});
Getting the Middleware Results and Error Handling
Because any argument passed to the Middleware Container (crud.create(arg1, arg2, fn1);
) will get piped to the middleware, we cannot add a callback within these arguments. Thus the function .done()
is provided, so you can check for errors or results.
crud.create(arg1, arg2, fn1).done(function(err) {
if (err) {
return console.error(err);
}
});
The only way to pass arguments back to the callback of the .done()
method is through the Final Callback that is defined in the make()
method.
var crud = {};
var lastMiddlware = function(done) {
done(null, 'one', 'two');
});
middlewarify.make(crud, 'create', lastMiddlware);
crud.create().done(function(err, arg1, arg2) {
if (err) { }
arg1 === 'one';
arg2 === 'two';
});
Beware of Error Handling Middlewarify will catch all thrown errors from your middleware. They will be piped to the .done()
method. So if any of your middleware functions throws an error, it will not be visible unless you setup the .done()
callback.
Why a .done() function
The trailling .done()
function will notify you of the ultimate outcome of the middleware execution. The problem for having the callback as an argument when invoking the middleware with tasks.create()
is that there is no way to determine if that is the callback to call when all middleware are done, or an argument that should be passed to all middleware.
This becomes more aparent when using the Before/After feature of Middlewarify which binds a before
and after
functions instead of use
.
var midd = require('middlewarify');
var tasks = module.exports = {};
function createTask(cb, done) {
anAsyncOp(function(err, result) {
if (err) {
cb(err);
done(err);
return;
}
cb(null, result);
done(null, result);
});
}
midd.make(tasks, 'create', createTask, {beforeAfter: true});
tasks.create.before(function(cb, next) {
next();
});
tasks.create.after(function(cb, result, next) {
next();
});
tasks.create(function(err, result, done){
done();
}).done(function(err, fn, result){
});
Release History
- v0.1.0, 28 Jan 2014
- Added Before/After feature
- Reorganized tests
- v0.0.4, 10 Oct 2013
- Added option to not throw errors
- v0.0.3, 02 Aug 2013
- Added a more explicit way to declare callbacks when invoking the middleware.
- v0.0.2, 15 JuL 2013
License
Copyright 2013 Thanasis Polychronakis
Licensed under the MIT License