AllenYuan

feed endpoint

May 20th, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //...
  2.  
  3. // feed from authors user is following
  4. router.get('/feed', auth.required, function(req, res, next){
  5.   // configure the query params
  6.   var limit = 20;
  7.   var offset = 0;
  8.  
  9.   if(typeof req.query.limit !== 'undefined'){
  10.     limit = req.query.limit;
  11.   }
  12.  
  13.   if(typeof req.query.offset !== 'undefined'){
  14.     offset = req.query.offset;
  15.   }
  16.  
  17.   // grab user from mongo
  18.   User.findById(req.payload.id).then(function(user){
  19.     if (!user) { return res.sendStatus(401); }
  20.  
  21.     // find the paginated list of articles for authors we're following
  22.     Promise.all([
  23.       Article.find({ author: {$in: user.following}})
  24.         .limit(Number(limit))
  25.         .skip(Number(offset))
  26.         .populate('author')
  27.         .exec(),
  28.       Article.count({ author: {$in: user.following}})
  29.     ]).then(function(results){
  30.       // return list of article JSON's
  31.       var articles = results[0];
  32.       var articlesCount = results[1];
  33.  
  34.       return res.json({
  35.         articles: articles.map(function(article){
  36.           return article.toJSONFor(user);
  37.         }),
  38.         articlesCount: articlesCount
  39.       });
  40.     }).catch(next);
  41.   });
  42. });
  43.  
  44. //...
Advertisement
Add Comment
Please, Sign In to add comment