Skip to content

Instantly share code, notes, and snippets.

@garrows
Created May 4, 2015 14:21
Show Gist options
  • Save garrows/b5f5894fb31eba77e0ac to your computer and use it in GitHub Desktop.
Save garrows/b5f5894fb31eba77e0ac to your computer and use it in GitHub Desktop.
Middleware Stacker
// In the express generated example, this is /routes/index.js
var express = require('express');
var router = express.Router();
var TheService = function() {};
TheService.prototype = {
getTitle: function(req, res, next) {
console.log('getTitle');
res.title = 'Express';
next();
},
renderPage: function(req, res, next) {
console.log('renderPage')
res.render('index', {
title: res.title
});
}
};
var service = new TheService();
var routes = [{
path: '/',
get: [service.getTitle, service.renderPage]
}]
var allowedHttpMethods = ['all', 'get', 'put', 'post', 'delete'];
for (var i = 0; i < routes.length; i++) {
var route = routes[i];
for (var j = 0; j < allowedHttpMethods.length; j++) {
var httpMethod = allowedHttpMethods[j],
middleware = route[httpMethod];
if (middleware instanceof Array) {
var args = [route.path].concat(middleware);
router[httpMethod].apply(router, args);
}
}
}
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment