oms/backend/app/lib/pagination.js
liufumingren 8597cf5ac9 feat(backend): 用户鉴权、菜单权限、主体与系统基础模块
- 登录/邮箱验证码/密码流程(controller/auth.js、lib/emailCode.js、middleware/jwt_auth.js)
- 主体(principal)隔离与主体用户、对外接口配置模块及 principalCheck 中间件
- 菜单、用户、文件上传、快递公司字典(express_companies)等基础模块
- 通用工具:分页(lib/pagination.js)、缓存(service/cache.js)
- 全量接口契约(contract/index.js)与路由注册(router.js)、config.default.js 配置
- 相关迁移:菜单组件调整与菜单种子、创建 files 表
2026-09-13 02:23:34 +08:00

64 lines
1.9 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/**
* 列表分页统一封装
* - 所有列表接口统一用 parsePagination 解析 page / pageSize,避免各控制器各写一套
* - pageSize 做了上限保护(默认 200),防止前端传入超大值把整表拉到内存
* - 列表响应体统一用 buildPageResult 组装,保证 { list, total, page, pageSize } 结构一致
*/
/** 默认每页条数 */
const DEFAULT_PAGE_SIZE = 20;
/** 每页条数上限 */
const MAX_PAGE_SIZE = 200;
/**
* 转为整数,非法值返回兜底值
* @param {*} value 原始值
* @param {Number} fallback 兜底值
* @return {Number} 整数
*/
function toInt(value, fallback) {
const num = Number.parseInt(value, 10);
return Number.isFinite(num) ? num : fallback;
}
/**
* 解析分页参数
* @param {Object} query ctx.query
* @param {Object} [options] defaultPageSize 默认每页条数(默认 20)、maxPageSize 上限(默认 200)
* @return {{page: Number, pageSize: Number, offset: Number, limit: Number}} 分页参数
*/
function parsePagination(query = {}, options = {}) {
const defaultPageSize = options.defaultPageSize || DEFAULT_PAGE_SIZE;
const maxPageSize = options.maxPageSize || MAX_PAGE_SIZE;
const page = Math.max(1, toInt(query.page, 1));
const pageSize = Math.min(maxPageSize, Math.max(1, toInt(query.pageSize, defaultPageSize)));
return { page, pageSize, offset: (page - 1) * pageSize, limit: pageSize };
}
/**
* 组装统一的分页响应数据
* @param {Array} rows 当前页数据
* @param {Number} total 总条数
* @param {Object} pageInfo 分页参数(parsePagination 的返回值或 { page, pageSize })
* @return {{list: Array, total: Number, page: Number, pageSize: Number}} 响应数据
*/
function buildPageResult(rows, total, pageInfo = {}) {
return {
list: rows,
total,
page: pageInfo.page,
pageSize: pageInfo.pageSize,
};
}
module.exports = {
DEFAULT_PAGE_SIZE,
MAX_PAGE_SIZE,
parsePagination,
buildPageResult,
};