Created
May 4, 2015 14:21
-
-
Save garrows/b5f5894fb31eba77e0ac to your computer and use it in GitHub Desktop.
Middleware Stacker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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