10

I have to build and API as server side, that should provide results in pages of 10 entries, using only Node with express (no other packages).

  • A query parameter p specifies which page to return, starting with 1. If the p parameter is omitted, the default value is 1.
  • If the client side asks for /api/stories?p=1, they should only get 10 stories, starting from the newest one.

  • If p=2, the API must return the second batch of 10 stories. When a page of stories is returned it must be ordered with the most recent story first.

  • If p is greater than the last page number, the API must return the last available page.

  • The page value is the currently returned page. If the requested page p is greater than the last page number, the returned page value will indicate the last page number.

  • The pageCount value is the number of the last non-empty page.*

This is what I have for pagination...

//pagination
const pageLimit = 10;
app.get('/api/posts', function(req, res) {
  res.json({
    "posts": posts.slice(-pageLimit).reverse(),
    "page": 1,
    "pageCount": Math.ceil(posts.length / 10)
  });
});

The return is correct as 10 posts per page, 11th, 21st, 31st posts are pushed on 2nd ,3rd page etc... Now my problem comes when I try to advance from page 1 to page 2 (as a next page) nothing happens...

I'm guessing I have to implement something like a a next but I don't have any idea how to do it

Any help would be appreciated...

5 Answers 5

21

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)
  });
});
3
  • upvoted! since you are returning json response i had to ask a question, if the person changes the data in the url and hits enter, how do you prevent them from seeing raw json on the screen
    – PirateApp
    Dec 25, 2018 at 7:48
  • easiest and simple way I came across!
    – Nibha Jain
    Aug 21, 2019 at 9:37
  • 1
    What is the value of posts? Where are you getting or defining? Nov 23, 2021 at 7:35
4

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.

3
  • no is just a test file with in-memory. No db involved....your solution is nearly what I need. Just try to figure out how to tweak because is trow some error as "ReferenceError: pages is not defined".
    – Gallex
    Dec 13, 2017 at 19:44
  • @Gallex fixed, my fault
    – num8er
    Dec 13, 2017 at 19:45
  • @Gallex fixed according correct size of posts count to not get out of bounds
    – num8er
    Dec 13, 2017 at 20:34
2
export default (limit, offset, count) => {
  const pageData = {};
  limit = limit > count ? count : limit;
  offset = offset > count ? count : offset;

  pageData.page = Math.floor(offset / limit) + 1;
  pageData.pageCount = Math.ceil(count / limit);
  pageData.pageSize = Number(limit);
  pageData.totalCount = count;

  return pageData;
};
1

You are almost there. You are missing a part, here's a practical example:

let records = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
];
let pageSize = 5;

function paginate(page = 1) {
    //when page is 1, we go from index 0 to index 4 
    //that's the first 5 records.
    return records.slice(pageSize * (page - 1), pageSize * page);
}

console.log(paginate(1));
console.log(paginate(2));
console.log(paginate(3));

https://jsfiddle.net/fe4s2qxv/

0

Node pagination with sequelize
client needs to provide page and pageSize

const page = 1
const pageSize = 2
const offset = page * pageSize
const limit = offset + pageSize
return model.findAll({
             attributes: [],
             include: [{}],
             limit,
             offset
       })
       .then((tasks) => res.status(200).send(tasks))
       .catch((error) => {
             console.log(error);
             res.status(400).send(error);
       });

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.