Abstract Mongoose to REST interface CRUD. In MVC paradigm this module is a way
to generate view (as JSON object) and controller for this particular model.
It is worth mention, that access control checks are performed via
static Active Record methods and
instance Active Record methods
mongoose model against the current authenticated user.
It is nodejs implementation of awesome module of (http://www.symfony-project.org/plugins/sfDoctrineRestGeneratorPlugin)
This work is inspired by http://www.restapitutorial.com/.
This module is intended to work with HuntJS framework of v 0.1.x branch.
var Hunt = require('hunt'),
hrw = require('hunt-mongo-rest'),
hunt = Hunt({
'disableCsrf': true,
'huntKey': true,
'mongoUrl': 'mongodb://localhost/hrw_dev'
});
hunt.extendModel('Articles', function(core){
var ArticleSchema = new core.mongoose.Schema({
'name': { type: String, unique: true },
'content': String,
'author': { type: core.mongoose.Schema.Types.ObjectId, ref: 'User' }
});
ArticleSchema.index({
'name': 1,
'author': 1
});
ArticleSchema.statics.doSmth = function (user, payload, callback) {
callback(null, {
'user': user,
'body': payload
});
};
ArticleSchema.methods.doSmth = function (user, payload, callback) {
callback(null, {
'article': this,
'user': user,
'body': payload
});
};
ArticleSchema.statics.canCreate = function (user, callback) {
if (user) {
callback(null, true, 'author');
} else {
callback(null, false);
}
};
ArticleSchema.statics.listFilter = function (user, callback) {
if (user) {
if (user.root) {
callback(null, {}, ['id', 'name', 'content', 'author'], ['author']);
} else {
callback(null, {'author': user._id}, ['id', 'name', 'content']);
}
} else {
callback(null, false);
}
};
ArticleSchema.methods.canRead = function (user, callback) {
if (user) {
if (user.root) {
callback(null, true, ['id', 'name', 'content', 'author'], ['author']);
} else {
callback(null, (this.author == user.id), ['id', 'name', 'content']);
}
} else {
callback(null, false);
}
};
ArticleSchema.methods.canUpdate = function (user, callback) {
if (user) {
if (user.root) {
callback(null, true, ['name', 'content', 'author']);
} else {
callback(null, this.author == user.id, ['name', 'content']);
}
} else {
callback(null, false);
}
};
ArticleSchema.methods.canDelete = function (user, callback) {
var document = this;
if (user) {
if (user.root) {
callback(null, true);
} else {
callback(null, document.author == user.id);
}
} else {
callback(null, false);
}
};
ArticleSchema.path('author').validate(function (value, respond) {
return core.model.User.findById(value, function (error, authorFound) {
if (error) {
throw error;
} else {
respond(authorFound ? true : false);
}
});
}, 'Unable to find Author!');
return core.mongoConnection.model('Article', ArticleSchema);
});
hrw(hunt, {
'mountPount' : '/api/v1/articles',
'modelName': 'Article',
'statics': ['doSmth'],
'methods':['doSmth']
});
Hunt.startWebServer();