Skip to content

Commit

Permalink
feat(helpers): add compose feature (#1660)
Browse files Browse the repository at this point in the history
  • Loading branch information
paulbakker authored and hekike committed May 16, 2018
1 parent a078fa0 commit eb60ef4
Show file tree
Hide file tree
Showing 3 changed files with 101 additions and 0 deletions.
34 changes: 34 additions & 0 deletions lib/helpers/chainComposer.js
@@ -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
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
@@ -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();
}
);
});

0 comments on commit eb60ef4

Please sign in to comment.