Skip to content

Instantly share code, notes, and snippets.

@turntayble81
Created January 20, 2014 03:43
Show Gist options
  • Save turntayble81/8514546 to your computer and use it in GitHub Desktop.
Save turntayble81/8514546 to your computer and use it in GitHub Desktop.
var router = exports,
fs = require('fs');
router.init = function(parent, map) {
var controllers = [],
_this = this;
function _loadControllers() {
fs.readdirSync(parent.get('controllers')).forEach(function(name) {
controllers[name.replace(/\.js$/, '')] = require(parent.get('controllers') + '/' + name);
});
}
function _setupRoutes() {
var route,
routes,
routeVal,
path,
method,
controller,
fn;
for(method in map) {
if(map.hasOwnProperty(method)) {
routes = map[method];
for(route in routes) {
if(routes.hasOwnProperty(route)) {
routeVal = routes[route];
path = routeVal.split('/');
if(path.length > 1) {
controller = path[0];
fn = path[1];
}
if(typeof(controllers[controller]) != 'object') {
throw new Error(parent.get('controllers') + '/' + controller + '.js does not exist.');
}
if(typeof(controllers[controller][fn]) != 'function') {
throw new Error(controller + " controller doesn't have a method named '" + fn + "'");
}
parent[method.toLowerCase()](route, controllers[controller][fn]);
}
}
}
}
}
_loadControllers();
_setupRoutes();
};
var router = require('./libraries/router');
app.set('controllers', path.join(__dirname, 'controllers'));
router.init(app, {
'GET': {
'/' : 'index/index',
'/login' : 'account/login'
},
'POST': {
'/login' : 'account/authenticate'
}
});
@turntayble81
Copy link
Author

Thought this would come in handy to automatically load controller files and set up routes..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment