Skip to content

Instantly share code, notes, and snippets.

@knownasilya
Last active January 3, 2016 03:39
Show Gist options
  • Save knownasilya/8403537 to your computer and use it in GitHub Desktop.
Save knownasilya/8403537 to your computer and use it in GitHub Desktop.
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
};
var express = require('express'),
userRoutes = require('./routes/user'),
helpers = require('./helpers'),
app = express();
// Middleware, etc..
helpers.initializeRoutes(app, [
userRoutes
]);
// start server..
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