Node pagination with express

Check this out:

app.get('/api/posts', (req, res) => {
  const postCount = posts.length;
  const perPage = 10;
  const pageCount = Math.ceil(postCount / perPage);

  let page = parseInt(req.query.p);
  if(page < 1) page = 1;
  if(page > pageCount) page = pageCount;

  const from = postCount - ((page - 1) * perPage) - 1; // ex.: 44 - ((1 - 1) * 10) -1 = 43 (44 is count, 43 is index)
  let to = postCount - (page * perPage); // ex.: 44 - (1 * 10) = 34
  if(to < 0) to = 0;

  res.json({
    posts: posts.slice(from, to).reverse(),
    page,
    pageCount
  });
});

P.S. If posts array retrieved from database - I strongly recommend to use database powers to retrieve necessary data. Otherwise retrieving thousands of page and then slicing array to 10 items is will result with performance issues.


after scratching my head 2 days, I found a solution that works for me..Thank you num8er for pointing me in right direction...

app.get('/api/posts', (req, res) => {
  const pageCount = Math.ceil(posts.length / 10);
  let page = parseInt(req.query.p);
  if (!page) { page = 1;}
  if (page > pageCount) {
    page = pageCount
  }
  res.json({
    "page": page,
    "pageCount": pageCount,
    "posts": posts.slice(page * 10 - 10, page * 10)
  });
});