generators and fetching all from a paginated api
Unanswered
Hooded Oriole posted this in #help-forum
Hooded OrioleOP
I've never used generators before. I was wondering if this is correct:
- i want to fetch all items in an api using do-while and also generators
- i want to fetch all items in an api using do-while and also generators
export async function* fetchAllItems<T>({
baseUrl = "https://api.example.com/things",
limit = 250,
}: {
baseUrl?: string;
limit?: number;
} = {}): AsyncGenerator<T, void, unknown> {
let cursor: string | null = null;
do {
const url = new URL(baseUrl);
url.searchParams.set("limit", String(limit));
if (cursor) url.searchParams.set("cursor", cursor);
const res = await fetch(url, { headers: { Accept: "application/json" } });
if (!res.ok) throw new Error(`HTTP ${res.status} fetching ${url}`);
const json = await res.json();
const items = (json?.items ?? []) as T[];
cursor = (json?.nextCursor ?? null) as string | null;
for (const item of items) yield item;
} while (cursor);
}