Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
48
rated 0 times [  52] [ 4]  / answers: 1 / hits: 24380  / 7 Years ago, wed, december 13, 2017, 12:00:00

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...


More From » json

 Answers
49

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)
});
});

[#55695] Friday, December 8, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
benitoh

Total Points: 150
Total Questions: 113
Total Answers: 104

Location: India
Member since Wed, Aug 26, 2020
4 Years ago
;