Create a gist now

Instantly share code, notes, and snippets.

@kkamkou /router.js
Last active Dec 10, 2015

What would you like to do?
express.js custom router (middleware)
/**
* @category Application
* @package Middleware
* @author Kanstantsin A Kamkou (kkamkou@gmail.com)
*/
// required
var fs = require('fs'),
express = require('express'),
path = require('path');
// defaults
var pathRouters = CONSTANTS.PATH_ROOT + '/config/routes',
pathController = CONSTANTS.PATH_APP + '/modules',
routerList = [], dejavu;
// exporting stuff
module.exports = function (req, res, next) {
// @see: https://gist.github.com/4351835
dejavu = req.app.get('dejavu');
// loading the routes and caching if needed
if (!dejavu || !dejavu.has('routerList')) {
// reading ftom the fs
routerList = fs.readdirSync(pathRouters);
// caching
if (dejavu) {
dejavu.set('routerList', routerList);
}
}
routerList.forEach(function (pathRoute) {
// defaults
var instance = express(),
rules = require(pathRouters + '/' + pathRoute),
mdlName = path.basename(pathRoute, '.json');
// configuaration
instance.set('moduleName', mdlName)
.set('views', [pathController, mdlName, 'views'].join('/'));
// building the navigation set
Object.keys(rules).forEach(function (controller) {
// loading module itself
var module = require(
[pathController, mdlName, 'controllers', controller].join('/')
);
// lets iterate the object to combine parts
Object.keys(rules[controller]).forEach(function (method) {
Object.keys(rules[controller][method]).forEach(function (mask) {
instance[method](rules[controller][method][mask], module[mask]);
});
});
// exporting it
req.app.use(instance);
});
});
// jumping up
next();
};
Owner

kkamkou commented Dec 20, 2012

Folder structure:

/app
  /modules
    /mymodule
      /controllers
        /index.js
      /views
        /mobile
        /desktop
        /tablet
        index.jade

Example of the route-file (/config/routes/moduleName.json):

{
  "ajax": {
    "get": {
      "subscribe": "/something/subscribe",
      "timer": "/something/timer"
    }
  },

  "index": {
    "get": {
      "pdf": "/something/pdf/:mail?",
      "list": "/something/:city/:name/:id/list"
    }
  }
}

Setup: as usual middleware, with require()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment