Skip to content

Instantly share code, notes, and snippets.

@richardzcode
Created December 5, 2011 23:47
Show Gist options
  • Save richardzcode/1435959 to your computer and use it in GitHub Desktop.
Save richardzcode/1435959 to your computer and use it in GitHub Desktop.
A bit more convenient way of routing when developing on expressjs. And add a context object to request
/**
* Path array: [method, pattern, function]
*
* Usage in app.js:
* var dispatcher = require('./routes').getDispatcher(app);
*
* dispatcher.routes('root',
* ['get', '/', 'index']
* );
*
* dispatcher.routes('auth',
* ['gp', '/auth/login', 'login'],
* ['post', '/auth/logout', 'logout'],
* ['gp', '/auth/signup', 'signup']
* );
*
* TODO: make the third element of path optional.
*/
function Dispatcher(app) {
// Create a shortcut for GET and POST.
app.gp = function() {
app.get.apply(app, arguments);
app.post.apply(app, arguments);
}
this.app = app;
}
module.exports.getDispatcher = function(app) {
return new Dispatcher(app);
}
/**
* routes(module_name, path1, path2, ...)
*/
Dispatcher.prototype.routes = function() {
var name = arguments[0];
var submodule = require('./' + name);
for (var i = 1; i < arguments.length; i ++) {
var entry = arguments[i];
if (entry.length < 3) {
continue;
}
var fn = this.app[entry[0]];
fn.call(this.app, entry[1], this.beforeEntry, submodule[entry[2]]);
}
}
/**
* Before every entry, add a context object to request.
* Common context variables can be added here.
*
* So in routes:
* exports.index = function(req, res) {
* ctx = req.context.extend({'title', 'Express'});
* res.render('index', ctx);
*/
Dispatcher.prototype.beforeEntry = function(req, res, next) {
req.context = new RequestContext();
next();
}
RequestContext = function() {}
RequestContext.prototype.extend = function(items) {
for (var itemname in items) {
this[itemname] = items[itemname];
}
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment