Files
services/utils/pagination.js
T

36 lines
1004 B
JavaScript
Raw Normal View History

2026-06-03 14:15:55 +08:00
/**
* 数据库分页查询工具函数
* @module services/utils/pagination
*/
/**
* 分页查询函数
* @param {Function} queryFn - 数据库查询函数
* @param {string} sql - SQL 查询语句
* @param {Array} params - SQL 参数
* @param {number} [page=1] - 页码
* @param {number} [pageSize=20] - 每页大小
* @returns {Promise<Object>} 分页结果 { data, total, page, pageSize, totalPages }
*/
2026-05-26 13:37:55 +08:00
async function paginate(queryFn, sql, params, page = 1, pageSize = 20) {
const p = Math.max(1, parseInt(page) || 1)
const ps = Math.min(100, Math.max(1, parseInt(pageSize) || 20))
const countResult = await queryFn(
`SELECT COUNT(*) as total FROM (${sql}) AS _paged`,
params
)
const total = countResult[0].total
const totalPages = Math.ceil(total / ps)
2026-05-26 14:04:14 +08:00
const offset = (p - 1) * ps
2026-05-26 13:37:55 +08:00
const data = await queryFn(
2026-05-26 14:04:14 +08:00
`${sql} LIMIT ${ps} OFFSET ${offset}`,
params
2026-05-26 13:37:55 +08:00
)
return { data, total, page: p, pageSize: ps, totalPages }
}
module.exports = { paginate }