AllenYuan

article favorite/unfavorite

May 11th, 2020
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //...
  2.  
  3. // favorite article
  4. router.post('/:article/favorite', auth.required, function(req, res, next) {
  5.   // extract id from posted article
  6.   var articleId = req.article._id;
  7.  
  8.   // find posted user, favorite the article, update favorite count, and return article
  9.   User.findById(req.payload.id).then(function(user){
  10.     if (!user) { return res.sendStatus(401); }
  11.  
  12.     return user.favorite(articleId).then(function(){
  13.       return req.article.updateFavoriteCount().then(function(article){
  14.         return res.json({article: article.toJSONFor(user)});
  15.       });
  16.     });
  17.   }).catch(next);
  18. });
  19.  
  20. // unfavorite. Ditto favorite method, but using user.unfavorite
  21. router.delete('/:article/favorite', auth.required, function(req, res, next) {
  22.   var articleId = req.article._id;
  23.  
  24.   User.findById(req.payload.id).then(function (user){
  25.     if (!user) { return res.sendStatus(401); }
  26.  
  27.     return user.unfavorite(articleId).then(function(){
  28.       return req.article.updateFavoriteCount().then(function(article){
  29.         return res.json({article: article.toJSONFor(user)});
  30.       });
  31.     });
  32.   }).catch(next);
  33. });
  34.  
  35. module.exports = router;
Advertisement
Add Comment
Please, Sign In to add comment