import type { Translate } from "@/app/lib/i18n/t"; export const EXPORT_PAGE_SIZE = 500; export const EXPORT_MAX_ROWS = 10_000; // Error messages are i18n codes; pages pass them to t(). export async function fetchAllForExport( fetchPage: (page0: number, size: number) => Promise<{ rows: T[]; total: number }>, ): Promise { const first = await fetchPage(0, EXPORT_PAGE_SIZE); if (first.total > EXPORT_MAX_ROWS) throw new Error("ExportTooManyRows"); const all = [...first.rows]; if (all.length >= first.total) return all; if (all.length === 0) throw new Error("ExportFailed"); // A short first page means the server capped its page size; continue at that size. const size = all.length < EXPORT_PAGE_SIZE ? all.length : EXPORT_PAGE_SIZE; for (let page = 1; all.length < first.total; page++) { const { rows, total } = await fetchPage(page, size); // Rows added or removed mid-export could make the file repeat or skip a row. if (total !== first.total) throw new Error("ExportFailed"); // Never ship a partial file: a short or empty page before total is a failure. if (rows.length < Math.min(size, first.total - all.length)) throw new Error("ExportFailed"); all.push(...rows); } return all; } export function exportErrorText(err: unknown, t: Translate): string { return err instanceof Error && err.message === "ExportTooManyRows" ? t("ExportTooManyRows", { max: EXPORT_MAX_ROWS.toLocaleString() }) : t("ExportFailed"); }