Skip to content

Commit

Permalink
initial code for mongoose wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
indutny committed Nov 18, 2010
1 parent a8fa545 commit 41a654c
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions modules/model.wrapper.mongoose.js
@@ -0,0 +1,54 @@
/**
* Wrap mongoose functions to CRUD
*
* So mongoose models will be compatible with "model.js" module
*/
exports.wrap = function(model, access) {
function __save(record, cb) {
record.save(function(errors, record) {
if (errors) return cb(errors, errors);

cb(null, record.toObject());
});
}

function __load(id, cb, success) {
model.findById(id, function(record) {
if (!record) return cb(true, {'record': 'not found'});

success ? success(record) : cb(null, record.toObject());
});
}

return {
access: access:
create: function(obj, cb) {
var record = new model(obj);

__save(record, cb);
},
read: function(id, cb) {
__load(id, cb);
}
update: function(id, obj, cb) {
__load(id, cb, function(record) {
record.hydrate(function() {
__save(record, cb);
}, obj);
})
}
delete: function(obj, cb) {
__load(id, cb, function(record) {
record.remove(function(errors) {
if (errors) return cb(errors, errors);

cb(null, {ok: 1};
});
});
},
authorize_create: model.authorize_create,
authorize_read: model.authorize_read,
authorize_update: model.authorize_update,
authorize_delete: model.authorize_delete
};
}

0 comments on commit 41a654c

Please sign in to comment.