Files
monkey-ai-web/src/helpers/paging.js
T
2026-10-15 16:33:46 +08:00

80 lines
3.7 KiB
JavaScript

/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 后端 common/page_info.go 的 GetPageQuery 对 page_size > 100 是**静默钳到
// 100**——不报错、不提示。因此前端"传个大 page_size 一次取全"的写法拿到的
// 永远只有前 100 条,且无从察觉。这类页面往往还带前端分页控件(Table 的
// pagination),管理员翻到最后一页会以为已经看完全部数据。
//
// collectPagedItems 按后端返回的 total 逐页取全,是这类"取全部"场景的统一写法。
export const ORG_PAGE_SIZE = 100;
const DEFAULT_MAX_PAGES = 20;
/**
* 逐页取全一个分页列表接口。
*
* @param {(page: number, pageSize: number) => Promise<any>} fetchPage
* 取单页的函数,返回 axios 响应;页码从 1 开始。
* @param {{pageSize?: number, maxPages?: number, shouldAbort?: () => boolean}} [options]
* shouldAbort 每页请求前调用;返回 true 立即停止翻页并返回已取到的数据。
* 调用方用它接入自己的竞态围栏(切企业/切实体时不再继续发请求)。
* @returns {Promise<{items: any[], total: number, message: string, truncated: boolean}>}
* items 已取到的全部条目(失败时保留已成功的页,不连带丢弃)
* total 后端报告的总条数;后端未返回时回落为已取到的条数
* message 首页即失败时的后端错误文案,否则为空
* truncated 是否因触达 maxPages 上限而未取完
*/
export async function collectPagedItems(fetchPage, options = {}) {
const pageSize = options.pageSize || ORG_PAGE_SIZE;
const maxPages = options.maxPages || DEFAULT_MAX_PAGES;
const items = [];
let message = '';
let truncated = false;
let total = 0;
for (let page = 1; page <= maxPages; page += 1) {
if (options.shouldAbort && options.shouldAbort()) {
return { items, total: total || items.length, message, truncated };
}
let response;
try {
response = await fetchPage(page, pageSize);
} catch (error) {
// 网络错误 / HTTP 错误会让 axios reject。首页失败继续抛给调用方,
// 保持它原有的 catch + showError 行为不变;**后续页失败必须吞掉**,
// 否则异常冒泡会让调用方跳过 setState,把已经取到的前几页一起丢掉
// ——那正是云脑任务时间线补页(R10)踩过并修掉的坑。
if (page === 1) throw error;
return { items, total: total || items.length, message, truncated };
}
if (!response?.data?.success) {
// 同上:首页业务失败才算整体失败,后续页保留已到手的数据。
if (page === 1) message = response?.data?.message || '';
return { items, total: total || items.length, message, truncated };
}
const pageItems = response.data.data?.items || [];
items.push(...pageItems);
total = Number(response.data.data?.total || 0);
if (pageItems.length < pageSize) break;
if (total > 0 && items.length >= total) break;
if (page === maxPages) truncated = true;
}
return { items, total: total || items.length, message, truncated };
}