Skip to content

Instantly share code, notes, and snippets.

@isterin
Last active January 2, 2016 15:29
Show Gist options
  • Save isterin/8324039 to your computer and use it in GitHub Desktop.
Save isterin/8324039 to your computer and use it in GitHub Desktop.
var _ = require('underscore');
// Helper function to iterate directory and get resources
var recursiveListFiles = function(path) {
if (path == undefined) {
return [];
}
var fs = require('fs');
var paths = _.map(fs.readdirSync(path), function(p) { return path + '/' + p});
var files = _.filter(paths, function(f) {
return fs.statSync(f).isFile();
});
var dirs = _.filter(paths, function(f) {
return fs.statSync(f).isDirectory();
});
return _.flatten(files.concat(_.map(dirs, function(d) { return this.recursiveListFiles(d) }, this)));
}
// Routing...
var routes = recursiveListFiles('./routes');
_.each(routes, function(r) {
var rMod = require(r);
if (!rMod.hasOwnProperty('routes')) {
console.warn("Module: " + r + " doesn't define any routes.");
}
else {
if (typeof(rMod.routes) == 'function' && rMod.routes.length == 1) {
rMod.routes(app);
}
else {
if (typeof(rMod.routes) == 'function') {
var routes = rMod.routes()
}
else {
var routes = rMod.routes
}
_.each(routes, function(val, path) {
_.each(val, function(bindFunc, httpMethod) {
var route = r.replace(/^\.\/routes|(\..*)$/g, '');
if (path.match(/^\//)) {
route = path
}
else if (path != '_') {
route = route + "/" + path
}
app[httpMethod](route, bindFunc);
});
});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment