Home > database >  While testing API containing pagination in postman facing skip value error
While testing API containing pagination in postman facing skip value error

Time:05-14

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

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

CodePudding user response:

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;
}
  • Related