You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js自定义分页工具类中实现动态键名?

解决Node.js分页工具类动态列表键名的问题

这是个很典型的工具类复用场景问题——你的分页工具目前把列表键名硬编码成了scores,所以不管在哪个控制器调用,都会返回这个固定键名。咱们只需要给getPagingData方法增加一个参数,用来动态指定列表的键名,就能完美解决这个问题。

修改分页工具类 pagination.js

咱们给getPagingData添加一个listKey参数,并且设置默认值为'scores'(这样原来的代码不需要改动就能继续正常工作,保证兼容性),然后用对象计算属性来动态生成键名:

exports.getPagination = function (page, size) { 
  const limit = size ? +size : 3; 
  const offset = page ? page * limit : 0; 
  return { limit, offset }; 
}; 

// 新增listKey参数,默认值为'scores'
exports.getPagingData = function (datas, page, limit, listKey = 'scores') { 
  const { count: total_items, rows: listData } = datas; 
  const current_page = page ? +page : 0; 
  const total_pages = Math.ceil(total_items / limit); 
  // 使用计算属性动态设置列表键名
  return { 
    total_items, 
    [listKey]: listData, 
    total_pages, 
    current_page 
  }; 
};

在控制器中调用

现在你可以根据不同的业务场景,传入对应的键名:

分数(scores)控制器(保持原有调用也能正常工作)

const { page, size, title } = req.query; 
const { limit, offset } = pagination.getPagination(page, size); 
// ...业务逻辑
.then(async (scores) => { 
  // 不传listKey,默认使用'scores'
  const resData = pagination.getPagingData(scores, page, limit); 
  response.ok(res, "load scores data", resData); 
})

返回结果和之前一致:

{ 
  "success": true, 
  "message": "load scores data", 
  "data": { 
    "total_items": 4222, 
    "scores": [ { "id": 3, ... } ],
    "total_pages": 1408,
    "current_page": 0
  } 
}

事件(events)控制器(传入指定键名)

// ...业务逻辑
.then(async (events) => { 
  // 传入'events'作为列表键名
  const resData = pagination.getPagingData(events, page, limit, 'events'); 
  response.ok(res, "load events data", resData); 
})

现在就能得到你预期的返回结果:

{ 
  "success": true, 
  "message": "load events data", 
  "data": { 
    "total_items": 4222, 
    "events": [ { "id": 3, ... } ],
    "total_pages": 1408,
    "current_page": 0
  } 
}

额外优化建议

如果你希望强制所有调用都必须传入listKey(避免忘记传导致返回不符合预期的键名),可以去掉默认值,并且在函数开头做简单的参数校验:

exports.getPagingData = function (datas, page, limit, listKey) { 
  // 校验listKey是否传入
  if (!listKey || typeof listKey !== 'string') {
    throw new Error('listKey must be a non-empty string');
  }
  const { count: total_items, rows: listData } = datas; 
  const current_page = page ? +page : 0; 
  const total_pages = Math.ceil(total_items / limit); 
  return { 
    total_items, 
    [listKey]: listData, 
    total_pages, 
    current_page 
  }; 
};

内容的提问来源于stack exchange,提问作者yogithesymbian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 21:04:07