AllenYuan

list articles

May 20th, 2020
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //...
  2.  
  3. // endpoint to list all articles
  4. router.get('/', auth.optional, function(req, res, next) {
  5.   // set query, limit, offset params for filtering/pagination.
  6.   var query = {};
  7.   var limit = 20;
  8.   var offset = 0;
  9.  
  10.   if(typeof req.query.limit !== 'undefined'){
  11.     limit = req.query.limit;
  12.   }
  13.  
  14.   if(typeof req.query.offset !== 'undefined'){
  15.     offset = req.query.offset;
  16.   }
  17.  
  18.   // return promise for [articles matching query, count, user]
  19.   return Promise.all([
  20.     Article.find(query)
  21.       .limit(Number(limit))
  22.       .skip(Number(offset))
  23.       .sort({createdAt: 'desc'})
  24.       .populate('author')
  25.       .exec(),
  26.     Article.count(query).exec(),
  27.     req.payload ? User.findById(req.payload.id) : null,
  28.   ]).then(function(results){
  29.     var articles = results[0];
  30.     var articlesCount = results[1];
  31.     var user = results[2];
  32.  
  33.     // return list of articles and articlesCount
  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. //...
Advertisement
Add Comment
Please, Sign In to add comment