express.js custom router (middleware)
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
/** | |
* @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(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Folder structure:
Example of the route-file (
/config/routes/moduleName.json
):Setup: as usual middleware, with require()