Skip to content

Instantly share code, notes, and snippets.

@markselby
Created December 26, 2014 16:51
Show Gist options
  • Save markselby/b4cdd582fadfb07216d2 to your computer and use it in GitHub Desktop.
Save markselby/b4cdd582fadfb07216d2 to your computer and use it in GitHub Desktop.
Node.js models and controllers
var grunt = require('grunt');
var controllers = [];
grunt.file.expand({ cwd: '' }, 'app/controllers/**/*.js').forEach(function(filename) {
// The routes in this file
var controller = require(process.cwd() + '/' + filename);
controller.filename = filename;
controller.priority = controller.priority || 1;
controllers.push(controller)
});
var keywords = ['filename', 'mountpoint', 'priority'];
controllers.sort(function(a, b) { return a.priority - b.priority; }).reverse().forEach(function(controller) {
// Assumes controllers are .js files
var name = controller.filename.replace('app/controllers', '').replace('.js', '');
var mountpoint = controller.mountpoint || name;
Object.keys(controller).forEach(function(route) {
// Ignore these keywords, they're not routes
if(keywords.indexOf(route) > -1) return;
var parts = route.split(' ');
var method = parts[0].toLowerCase();
var url = (mountpoint + parts[1]).replace('//', '/').replace('/*', '*');
console.log('Mounting', method, url, mountpoint);
app.use(router[method](url, controller[route]));
allRoutes.push({ path: url, method: method });
});
});
var grunt = require('grunt');
global.m = {};
function camelize(str) {
return str.replace (/(?:^|[-])(\w)/g, function (_, c) {
return c ? c.toUpperCase () : '';
});
}
grunt.file.expand({ cwd: '' }, 'app/models/**/*.js').forEach(function(filename) {
// Load the model
var model = require(process.cwd() + '/' + filename);
// Assumes models are .js files
var name = filename.replace('app/models/', '').replace('.js', '').split('/');
var current = global.m;
var part;
while(part = name.shift()) {
if(name.length) {
n = camelize(part);
if(!current[n]) current = current[n] = {};
}
else {
current[part] = model;
model.type = part;
model._before_save = [];
model.before_save = [];
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment