Last active
January 3, 2016 03:39
-
-
Save knownasilya/8403537 to your computer and use it in GitHub Desktop.
Autoload routes - based on http://blog.harrywolff.com/smarter-express-routing/
This file contains hidden or 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
var _ = require('lodash'), | |
VALID_METHODS = ['get', 'put', 'post', 'delete']; | |
/** | |
Initializes the express server with routes defined in seperate modules. | |
Route modules should export valid http method arrays, with objects | |
in the following form `{ path: string, callback: function }`. | |
@param server - express app instance | |
@param routeModules - required route modules | |
@return | |
*/ | |
function initializeRoutes (server, routeModules) { | |
if (!server || !routeModules) { | |
throw new Error('Could\'t initialize express routes.'); | |
} | |
routeModules.forEach(function (module) { | |
_.forOwn(module, function (value, key) { | |
key = key.toLowerCase(); | |
// Only allow valid http methods | |
if (VALID_METHODS.indexOf(key) !== -1) { | |
module[key].forEach(function (route) { | |
server[key].call(server, route.path, route.callback); | |
}); | |
} | |
}); | |
}); | |
} | |
// Available helpers API | |
module.exports = { | |
initializeRoutes: initializeRoutes | |
}; |
This file contains hidden or 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
var express = require('express'), | |
userRoutes = require('./routes/user'), | |
helpers = require('./helpers'), | |
app = express(); | |
// Middleware, etc.. | |
helpers.initializeRoutes(app, [ | |
userRoutes | |
]); | |
// start server.. |
This file contains hidden or 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
var route = { | |
path: '/users/:id', | |
callback: function (req, res) { | |
// route code here.. | |
} | |
}; | |
module.exports = { | |
get: [route] | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment