Skip to content

Instantly share code, notes, and snippets.

@garrows

garrows/index.js

Created May 4, 2015
Embed
What would you like to do?
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