Skip to content

Instantly share code, notes, and snippets.

@edinella
Created December 9, 2014 17:04
Show Gist options
  • Save edinella/3af1420cde3d1a964075 to your computer and use it in GitHub Desktop.
Save edinella/3af1420cde3d1a964075 to your computer and use it in GitHub Desktop.
// request context
function Context(reqArgs, entity) {
this.req = reqArgs.req;
this.res = reqArgs.res;
this.next = reqArgs.next;
this.entity = entity;
}
Context.prototype.handleErrors = function(fn) {
var context = this;
return function(err) {
if (!err) {
return context.next(err);
}
Array.prototype.shift.apply(arguments);
return fn.apply(context, arguments);
};
};
Context.prototype.respond = function(status) {
var context = this;
return function(data) {
return context.res.status(status || 200).send(data);
};
};
Context.prototype.model = function(modelName) {
return mongoose.model(modelName || this.entity.modelName);
};
// request handler
function handle(fn) {
return function() {
var context = new Context(arguments, this);
var done = context.handleErrors(context.respond(201));
return fn.apply(context, done);
};
}
// entity
function Entity(modelName) {
this.modelName = this.Model.modelName;
}
Entity.prototype.create = handle(function() {
var done = this.handleErrors(this.respond(201));
this.entity.getModel().create(this.req.body, done);
});
Entity.prototype.index = handle(function() {
var done = this.handleErrors(this.respond(200));
this.entity.getModel().find({}).sort({createdAt: -1}).exec(done);
});
Entity.prototype.show = handle(function() {
var id = this.req.param('_id');
var done = this.handleErrors(this.respond(200));
this.entity.getModel().findById(id, done);
});
Entity.prototype.update = handle(function() {
var id = this.req.param('_id');
var done = this.handleErrors(this.respond(200));
this.entity.getModel().findByIdAndUpdate(id, this.req.body, done);
});
Entity.prototype.destroy = handle(function() {
var id = this.req.param('_id');
var done = this.handleErrors(this.respond(200));
this.entity.getModel().findByIdAndUpdate(id, {deleted: Date.now()}, done);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment