Skip to content

Instantly share code, notes, and snippets.

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

Embed
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();
};
@kkamkou

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.