diff --git a/lib/helpers/chainComposer.js b/lib/helpers/chainComposer.js new file mode 100644 index 000000000..530dc79c7 --- /dev/null +++ b/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); + }; +} diff --git a/lib/index.js b/lib/index.js index 6097b7098..87eb2192b 100644 --- a/lib/index.js +++ b/lib/index.js @@ -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') }; diff --git a/test/chainComposer.test.js b/test/chainComposer.test.js new file mode 100644 index 000000000..63fddb4af --- /dev/null +++ b/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(); + } + ); +});