Skip to content

Instantly share code, notes, and snippets.

@Vengarioth
Created May 9, 2014 14:59
Show Gist options
  • Save Vengarioth/e7dcdd9b3e8ac5df990d to your computer and use it in GitHub Desktop.
Save Vengarioth/e7dcdd9b3e8ac5df990d to your computer and use it in GitHub Desktop.
Wrapper arround express.js routing/middleware & mongoose to easily create REST API Objects
var restObject = function(name, collection) {
this.name = name;
this.collection = collection;
};
restObject.prototype.register = function(app) {
var that = this;
app.get('/api/' + this.name, function(req, res) {
that.getAll(function(err, models) {
if(err) {
res.send(400, err);
return;
}
res.jsonp(models);
});
});
app.post('/api/' + this.name, function(req, res) {
that.create(req.body, function(err, model) {
if(err) {
res.send(400, err);
return;
}
res.jsonp(model);
});
});
app.get('/api/' + this.name + '/:idParameter', function(req, res) {
res.jsonp(req.model);
});
app.put('/api/' + this.name + '/:idParameter', function(req, res) {
that.update(req, res);
});
app.del('/api/' + this.name + '/:idParameter', function(req, res) {
that.destroy(req.model, function(err, success) {
if(err) {
res.send(400, err);
return;
}
res.jsonp(success);
});
});
app.param('idParameter', function(req, res, next, idParameter) {
that.get(idParameter, function(err, model) {
if(err) {
next(err);
return;
}
req.model = model;
next();
});
});
};
restObject.prototype.get = function(id, callback) {
this.collection.findOne({name: id}, function(err, model) {
if(err) {
callback(err, null);
return;
}
if(!model) {
callback(new Error('could not find model with name ' + id), null);
return;
}
callback(null, model);
});
};
restObject.prototype.create = function(data, callback) {
var model = new this.collection(data);
model.save(function(err) {
if(err) {
callback(err, null);
return;
}
callback(null, model);
});
};
restObject.prototype.getAll = function(callback) {
this.collection.find().sort('-created').exec(function(err, models) {
if(err) {
callback(err, null);
return;
}
callback(null, models);
});
};
restObject.prototype.update = function(data, model, callback) {
for(var i in this.collection.schema.paths) {
console.log(i);
}
callback(null, model);
};
restObject.prototype.destroy = function(model, callback) {
model.remove(function(err) {
if(err) {
callback(err, null);
return;
}
callback(null, true);
});
};
module.exports = restObject;
/** Example route **/
var restObject = require('../lib/restObject.js'),
mongoose = require('mongoose'),
TestModel = mongoose.model('TestModel');
module.exports = function(app) {
var test = new restObject('testModel', TestModel);
test.register(app);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment