Last active
August 29, 2015 13:58
-
-
Save William-Yeh/10245319 to your computer and use it in GitHub Desktop.
load all Node.js (including Express) route definitions
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
/** | |
* load all Node.js (including Express) route definitions. | |
* in most cases you should only need to modify the app_routes[] array. | |
* | |
* inspired by the article: | |
* - http://stackoverflow.com/questions/5778245/expressjs-how-to-structure-an-application | |
* | |
* @author William Yeh <[email protected]> | |
* @date 2014-04-09 | |
* @license MIT | |
* | |
* @url https://gist.github.com/William-Yeh/10245319 | |
*/ | |
"use strict"; | |
/** | |
* route definitions (corresponding to ./routes/*.js files) | |
var app_routes = [ | |
'index' // ./routes/index.js | |
, 'route1' // ./routes/route1.js | |
, 'route2' // ./routes/route2.js | |
]; | |
*/ | |
/** | |
* init route mappings | |
* | |
* @param {array} app_routes - route names | |
*/ | |
exports.loadRoutes = function(app_routes) { | |
if (! Array.isArray(app_routes)) | |
return; | |
app_routes.map( function(route_name) { | |
if (typeof route_name !== 'string') | |
return; | |
console.log("Loading route: " + route_name); | |
// load individual routes dynamically | |
var route = require('./routes/' + route_name); | |
// invoke this route's init(), if any | |
if (typeof route.init === "function") { | |
route.init(); | |
} | |
}); | |
}; | |
/** | |
* init route mappings | |
* | |
* @param app - Express app object | |
* @param {array} app_routes - route names | |
*/ | |
exports.loadExpressRoutes = function(app, app_routes) { | |
app.disable('x-powered-by'); | |
if (! Array.isArray(app_routes)) | |
return; | |
app_routes.map( function(route_name) { | |
if (typeof route_name !== 'string') | |
return; | |
console.log("Loading route: " + route_name); | |
// load individual routes dynamically | |
var route = require('./routes/' + route_name); | |
// invoke this route's init(), if any | |
if (typeof route.init === "function") { | |
route.init(app); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment