Created
January 20, 2014 03:43
-
-
Save turntayble81/8514546 to your computer and use it in GitHub Desktop.
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
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(); | |
}; |
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
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' | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thought this would come in handy to automatically load controller files and set up routes..