Skip to content

Commit

Permalink
feature: add support for middlewares
Browse files Browse the repository at this point in the history
  • Loading branch information
SFantasy committed Oct 13, 2016
1 parent ace8561 commit e84d787
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
7 changes: 6 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// Module dependencies
const glob = require('glob');

const compose = require('./lib/compose');

const METHOD_ENUM = ['get', 'post', 'put', 'delete'];

function loadRouter(app, root, options) {
Expand All @@ -21,11 +23,14 @@ function loadRouter(app, root, options) {
methods.forEach((method) => {
let handler = controller[method];
let modifiedUrl = url;
let middlewares = [];

const methodLower = method.toLowerCase();

switch (typeof handler) {
case 'object':
modifiedUrl += `/${handler.params.join('/')}`;
middlewares = handler.middlewares || [];
handler = handler.handler;
break;
case 'function':
Expand All @@ -40,7 +45,7 @@ function loadRouter(app, root, options) {
} else if (METHOD_ENUM.indexOf(methodLower) !== -1) {
app[methodLower](rewriteRules.has(modifiedUrl) ?
rewriteRules.get(modifiedUrl) :
modifiedUrl, handler);
modifiedUrl, compose(middlewares), handler);
} else {
throw Error('[load-router]: invalid method: ', methodLower);
}
Expand Down
22 changes: 22 additions & 0 deletions lib/compose.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* Compose middlewares
*
* @param middlewares
* @returns {Function}
*/
function compose(middlewares) {
if (!Array.isArray(middlewares)) throw 'middlewares should be an Array of functions.';

for (const fn of middlewares) {
if (typeof fn !== 'function') throw 'middleware should be a function';
}

return (req, res, next) => {
(function iterate(i, max) {
if (i === max) return next();
middlewares[i](req, res, iterate.bind(this, i + 1, max));
})(0, middlewares.length);
}
}

module.exports = compose;

0 comments on commit e84d787

Please sign in to comment.