21 lines
567 B
JavaScript
21 lines
567 B
JavaScript
|
|
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)
|
||
|
|
|
||
|
|
const data = await queryFn(
|
||
|
|
`${sql} LIMIT ? OFFSET ?`,
|
||
|
|
[...params, ps, (p - 1) * ps]
|
||
|
|
)
|
||
|
|
|
||
|
|
return { data, total, page: p, pageSize: ps, totalPages }
|
||
|
|
}
|
||
|
|
|
||
|
|
module.exports = { paginate }
|