A
A
Alexander Koshelev2018-09-16 18:12:39
Node.js
Alexander Koshelev, 2018-09-16 18:12:39

How to pass page '/' as page '/1' for pagination in node.js?

Good afternoon everyone, I wanted to start rendering pagination, but I ran into the following problem:
I'm pulling data from the database, displaying 10 records per page, but the whole problem is in the main page '/'. Pages '/' and '/1' should display the same data (last 10 records), but I can't set the offset to the main page (on page '/1' it is calculated) which is calculated by the formula limit * (page - 1 ), That is, when the user goes to the '/1' page, everything works, but he will initially go to the '/' page, and now nothing will be displayed on it, since the offset takes a negative value and an error is generated, how can I fix this problem? so that both '/' and '/1' are treated as '/1'
here is the code

router.get('/:page?', async (req, res, next) => {
  let limit = 10;
  let offset = 0;
  try {
      let { page = null } = req.params;
      console.log(page);
      console.log(req.params.page);
      if (page !== null) {
         page = Number(page);

         if (Number.isNaN(page)) {
             next();

             return;
         }
      }

      const result = await User.findAll({
        limit: limit,
        offset: offset,//limit * (page - 1),
        order: [
          ['id', 'DESC']
        ]
      })
      res.render('index', { result });

      //.catch(console.log.bind(console));
      //console.log(result);
  } catch (e) {
    next(e);
  }
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-09-16
@Xandr24

If you want 1 in the absence of a value - well, use 1 as the default value, replace null with 1 in . And now you have
just due to the fact that null is converted to 0 when calculating offset, 0 - 1how much will be - you understand.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question