Files
bookstack/ts/bookstack.helpers.ts

33 lines
992 B
TypeScript

import type { IBookStackListResponse } from './bookstack.interfaces.js';
/**
* Auto-paginate a BookStack list endpoint using offset/count.
* If opts includes a specific offset, returns just that single page (no auto-pagination).
*/
export async function autoPaginate<T>(
fetchPage: (offset: number, count: number) => Promise<IBookStackListResponse<T>>,
opts?: { offset?: number; count?: number },
): Promise<T[]> {
const count = opts?.count || 100;
// If caller requests a specific offset, return just that page
if (opts?.offset !== undefined) {
const result = await fetchPage(opts.offset, count);
return result.data;
}
// Otherwise auto-paginate through all pages
const all: T[] = [];
let offset = 0;
while (true) {
if (offset > 0) {
await new Promise((r) => setTimeout(r, 100));
}
const result = await fetchPage(offset, count);
all.push(...result.data);
offset += count;
if (offset >= result.total) break;
}
return all;
}