Home > database >  Node JS - Simple Pagination - How to use Middleware in the route?
Node JS - Simple Pagination - How to use Middleware in the route?

Time:06-28

I'm new to Node and Express. I am currently adding a pagination function to my API. Most of the hard work is done so far, but I can't make it work since I've refactored and made the pagination a function.

Here is my route:

const projects = require('../controllers/project.controller');

module.exports = (app) => {
  var router = require('express').Router();
  // Retrieve all project
  router.get('/', projects.findAll);
};

Here is the middleware:

const paginatedResults = (model) => {
  return (req, res, next) => {
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;

    const results = {};
    if (endIndex < model.length) {
      results.next = {
        page: page   1,
        limit: limit,
      };
    }
    if (startIndex > 0) {
      results.previous = {
        page: page - 1,
        limit: limit,
      };
    }
    results.results = model.slice(startIndex, endIndex);
    res.paginatedResults = results;
    next();
  };
};

const pagination = {
  paginatedResults,
};

module.exports = pagination;

Here is my controller:

exports.findAll = (req, res) => {
  Project.find({}, (err, data) => {
    res.send(data);
  });
};

I'm just wondering is there something I should change within the function? Ideally I'd like to be able to use in the route (e.g. router.get('/', [pagination.paginatedResults(Projects), projects.findAll]))

CodePudding user response:

middlewares work one by one. You try to paginate when you have no results to paginate. If you are fine with using helper function, Try something like this.

//route
const projects = require('../controllers/project.controller');

module.exports = (app) => {
  var router = require('express').Router();
  // Retrieve all project
  router.get('/', projects.findAll);
};


// controller
exports.findAll = (req, res) => {
  const mongoQuery = Project.find();
  const result = await paginateQuery(mongoQuery, req.query.page, req.query.limit);
  res.send(result)
};

// helper
const paginateQuery =async (mongoQuery, page, limit) => {
  const skip = page-1
  const  results =await mongoQuery.skip(skip).limit(limt)
  // transform results the way you want and/or build response object
  return results

};
  • Related