Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions lib/helpers/chainComposer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'use strict';
/* eslint-disable func-names */

var Chain = require('../chain');
var _ = require('lodash');

module.exports = composeHandlerChain;

/**
* Builds a function with the signature of a handler
* function(req,resp,callback).
* which internally executes the passed in array of handler function as a chain.
*
* @param {Array} [handlers] - handlers Array of
* function(req,resp,callback) handlers.
* @param {Object} [options] - options Optional option object that is
* passed to Chain.
* @returns {Function} Handler function that executes the handler chain when run
*/
function composeHandlerChain(handlers, options) {
var chain = new Chain(options);
if (_.isArray(handlers)) {
handlers = _.flattenDeep(handlers);
handlers.forEach(function(handler) {
chain.add(handler);
});
} else {
chain.add(handlers);
}

return function handlerChain(req, resp, callback) {
chain.run(req, resp, callback);
};
}
1 change: 1 addition & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,4 @@ module.exports.createServer = createServer;
module.exports.formatters = require('./formatters');
module.exports.plugins = require('./plugins');
module.exports.pre = require('./plugins').pre;
module.exports.helpers = { compose: require('./helpers/chainComposer') };
66 changes: 66 additions & 0 deletions test/chainComposer.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
'use strict';
/* eslint-disable func-names */

if (require.cache[__dirname + '/lib/helper.js']) {
delete require.cache[__dirname + '/lib/helper.js'];
}
var helper = require('./lib/helper.js');

///--- Globals

var test = helper.test;
var composer = require('../lib/helpers/chainComposer');

test('chainComposer creates a valid chain for a handler array ', function(t) {
var counter = 0;
var handlers = [];
handlers.push(function(req, res, next) {
counter++;
next();
});

handlers.push(function(req, res, next) {
counter++;
next();
});

var chain = composer(handlers);
chain(
{
startHandlerTimer: function() {},
endHandlerTimer: function() {},
closed: function() {
return false;
}
},
{},
function() {
t.equal(counter, 2);
t.done();
}
);
});

test('chainComposer creates a valid chain for a single handler', function(t) {
var counter = 0;
var handlers = function(req, res, next) {
counter++;
next();
};

var chain = composer(handlers);
chain(
{
startHandlerTimer: function() {},
endHandlerTimer: function() {},
closed: function() {
return false;
}
},
{},
function() {
t.equal(counter, 1);
t.done();
}
);
});