Files
group-2-threaded-project-pe…/web/lib/fetchAllPages.js
2026-04-20 22:01:15 -06:00

23 lines
619 B
JavaScript

//Fetches every page from a paginated API and returns all items in one array
export async function fetchAllPages(urlBuilder) {
const items = [];
let page = 0;
let totalPages = 1;
while (page < totalPages) {
const res = await fetch(urlBuilder(page));
if (!res.ok) {
const body = await res.text().catch(() => '')
const detail = body ? `: ${body.slice(0, 200)}` : ''
throw new Error(`HTTP ${res.status}${detail}`)
}
const data = await res.json();
items.push(...(data.content ?? []));
totalPages = Math.max(data.totalPages ?? 1, 1);
page += 1;
}
return items;
}