Skip to content

Instantly share code, notes, and snippets.

@nijikokun
Last active August 29, 2015 14:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nijikokun/cc7b67148511d7d37027 to your computer and use it in GitHub Desktop.
Save nijikokun/cc7b67148511d7d37027 to your computer and use it in GitHub Desktop.
Reverse-routing done right for Express 3/4

Reverse Routing for Express

Benefits:

  • Reverse routing (with query support)
  • Enforcement of utilizing Controllers
  • Global middleware per Controller
  • Seperate method from middleware for testability
  • Probably other things.. but those are the most important.
var app = express();
// Initialize router
var router = require('./router')(app);
// Import routes (relative to router location)
//
// ./router.js -> ./:filename
//
// 'site' -> expands to -> ./site.js
router.import([
'site'
]);
var querystring = require('querystring');
var reverse = require('reverse-path');
var lodash = require('lodash');
module.exports = function (app) {
app.locals.reverse = function (name, options, query) {
var path = app.routes[name];
return path ? reverse(path, options) + (query ? querystring.stringify(query) : '') : '';
};
app.use(function (req, res, next) {
res.reverse = app.locals.reverse;
next();
});
return {
import: function importRoutes (files) {
app.routes = {};
lodash.each(files, function (filename) {
var router = require('./' + filename);
var middleware = router.middleware;
var routes;
delete router.middleware;
routes = Object.keys(router);
lodash.forEach(routes, function (name) {
var route = router[name];
// Setup middleware array
route.middleware = route.middleware || [];
// Concat global middleware
if (middleware) {
route.middleware = middleware.concat(route.middleware);
}
// Setup route
global.log.debug('Setting up route', route.method, route.name, route.path);
app[route.method](route.path, route.middleware, route.controller);
app.routes[route.name] = route.path;
});
});
}
};
};
var csurf = require('csurf');
/**
* Controller Middleware
*
* Applies to all routes in this controller.
*
* @type {Array}
*/
exports.middleware = [
csurf()
];
/**
* Site index view
*
* @type {Object}
*/
exports.index = {
method: 'get',
name: 'index',
path: '/',
controller: function (req, res) {
res.redirect(req.user ?
res.reverse('dashboard') :
res.reverse('login'));
}
};
/**
* Dashboard view
*
* @type {Object}
*/
exports.dashboard = {
method: 'get',
name: 'dashboard',
path: '/dashboard',
// Authentication middleware, or route specific middleware
// middleware: [isAuthorized],
controller: function (req, res) {
res.render('dashboard', {
user: req.user
})
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment