Files
zkxw/web-admin/src/utils/fetch-paged-list.ts
T
2026-05-17 08:36:37 +08:00

30 lines
1.0 KiB
TypeScript

/**
* 分页循环请求直至拿全数据(接口需返回 { list, total })。
* 用于分类、单位、用户等列表接口,避免只取第一页导致下拉选项不全。
*/
/** 与后端 `/web/admin/*` 列表普遍 `Query(..., le=100)` 一致,超出会 422 */
export const MAX_ADMIN_LIST_PAGE_SIZE = 100
export async function fetchAllPagedRecords<T>(
fetchPage: (page: number, pageSize: number) => Promise<{ list?: T[]; total?: number }>,
options?: { pageSize?: number; maxPages?: number }
): Promise<T[]> {
const requested = options?.pageSize ?? MAX_ADMIN_LIST_PAGE_SIZE
const pageSize = Math.min(Math.max(1, requested), MAX_ADMIN_LIST_PAGE_SIZE)
const maxPages = options?.maxPages ?? 50
let page = 1
const all: T[] = []
let total = 0
while (page <= maxPages) {
const res = await fetchPage(page, pageSize)
total = res.total ?? 0
const list = res.list ?? []
all.push(...list)
if (list.length === 0 || all.length >= total || list.length < pageSize) break
page += 1
}
return all
}