Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

While testing API containing pagination in postman facing skip value error

I am using pagination middleware in my node js project but while testing api in postman it’s throwing error skip value

Followed the paginate docs but still no use
While testing api in which pagination is applied it's throwing error

below is my pagination middleware

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    const pagination = (model) => {
  return async (req, res, next) => {
    const limit = parseInt(req.query.limit);
    const page = parseInt(req.query.page);

    if (page < 1 || page == undefined) {
      page = 1;
    }
    if (limit < 1 || limit == undefined) {
      limit = 2;
    }
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;
    const result = {};
    model.countDocuments({}, (err, count) => {
      const lengthOfDB = count;
      if (endIndex < lengthOfDB) {
        result.next = {
          page: page + 1,
          //limit: limit,
        };
      }
    }).clone();

    if (startIndex > 0) {
      result.previous = {
        page: page - 1,
        //limit: limit,
      };
    }
    try {
      result.result = await model.find().limit(limit).skip(startIndex).exec();
      res.json(result);
    } catch (e) {
      res.status(500).json({ message: e.message });
    }
  };
};

>Solution :

If page is not provided in the query, it will end up being NaN, since this code does not cover that case:

// 'req.query.page' is undefined
let page = parseInt(req.query.page);
if (page < 1 || page == undefined) {
    page = 1;
}
// 'page' is now equal to NaN

A correct way to handle this could be:

let page = parseInt(req.query.page);
if (page < 1 || isNaN(page)) {
    page = 1;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading