简体   繁体   English

Node JS - 简单分页 - 如何在路由中使用中间件?

[英]Node JS - Simple Pagination - How to use Middleware in the route?

I'm new to Node and Express.我是 Node 和 Express 的新手。 I am currently adding a pagination function to my API.我目前正在向我的 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 (eg router.get('/', [pagination.paginatedResults(Projects), projects.findAll]) )理想情况下,我希望能够在路由中使用(例如router.get('/', [pagination.paginatedResults(Projects), projects.findAll])

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

};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM