Skip to content

Instantly share code, notes, and snippets.

@PistachioPony
Last active August 29, 2015 13:56
Show Gist options
  • Save PistachioPony/9220394 to your computer and use it in GitHub Desktop.
Save PistachioPony/9220394 to your computer and use it in GitHub Desktop.
How the Validator Works
var mariaItem = function (req, res, next) {
Item.findOne({ _id: "5099803df3f4948bd2f98391"}, function (err, result){
req.contents = {};
req.contents.result = result;
next();
});
};
var mariaView = function (req, res, next){
async.waterfall([
function(callback){
Item.findOne({ _id: "5099803df3f4948bd2f98391"}, function (err, result){
req.contents = {};
req.contents.result = result;
callback();
});
},
function(callback){
User.findOne({ _id: req.contents.result.seller.sellerId}, function (err, result) {
req.contents.seller = result;
callback();
});
},
function(callback){
Group.find({ _id: {$in: req.contents.result.groups}}, function (err, result){
req.contents.groups = result;
callback();
});
},
function(callback){
var newComment = {};
newComment.commenterId = req.user._id;
newComment.commenterName = req.user.username;
newComment.body = req.body.comments;
Item.findOneAndUpdate({_id: "5099803df3f4948bd2f98391"}, {$addToSet: {comments: newComment} }, function (err, result) {
callback();
});
}
], function(err, results){
res.json(req.contents);
});
};
// +++++++++++++++ VALIDATION ++++++++++++++++++++
var validateMaria = function (req, res, next){
var Validator = function(seller){
this.seller = seller;
};
Validator.prototype.onlySeller = function() {
if (req.params._id == this.seller.sellerId) {
next();
} else{
res.json("You are not the seller!");
}
};
var thing = new Validator(req.contents.result.seller);
thing.onlySeller();
};
app.get('/maria/item', //when you hit this route it goes to mariaItem and gets the info and puts it in req.contents.results
mariaItem,
validateMaria,
//then it goes to the validateMaria function which creates a Validator object and a prototype of that object called
//onlySeller. then it creates a new Validator object called thing that takes the contentsof the findOne query from mariaItem.
//and then we call thing with its prototype (thing.onlySeller) which checks to see if you are the seller and gives an error if not!!
mariaView
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment