BACK_TO_COURSE
Pulling Data In
Paging: The Half-Report Nobody Notices
The Most Believable Wrong Number
APIs hand out long lists in pages. If a day has 412 calls at 100 per page, that's 5 pages: four full ones and one with 12.
Code that forgets paging gets page one. No error. A 200. A report that says 100 calls, missing 312 of them, with a nice chart on top.
The Two Main Kinds
- Offset or page number: "skip 100, give me the next 100." If the list changes while you're reading it, rows slide. With newest first, a new call pushes one you already have onto your next page. A deletion pulls one back past you, and you miss it.
- Cursor: the API gives you a bookmark for the next page. Usually sturdier. You keep going until there's no bookmark.
Here's what a correct loop looks like. Read it for the checks, not the syntax. (getPage is in the next lesson.)
async function pullCalls(from, to) {
const calls = new Map(); // one entry per call ID, so repeats collapse
let cursor = null;
do {
const url = new URL("/v1/calls", process.env.API_BASE);
url.searchParams.set("from", from);
url.searchParams.set("to", to);
url.searchParams.set("limit", "100");
if (cursor) url.searchParams.set("cursor", cursor);
const page = await getPage(url);
for (const call of page.data) calls.set(call.id, call);
const next = page.next_cursor ?? null;
if (next && next === cursor) {
throw new Error("Same cursor twice, stopping");
}
cursor = next;
} while (cursor); // keep going until there is no next page
return [...calls.values()];
}
Your Check
- Pick a day with more than one page. A slow Sunday proves nothing.
- Match the count to the vendor's own report for that same day.
- Be suspicious of round numbers. Exactly 100, 500 or 1,000 is usually a page limit wearing a costume.
- Check the edges. Does
toinclude that last moment, or stop just before it? Docs often don't say. Test with a call right at the line.
QUIZ
A day has 412 calls and the API returns 100 per page. How many pages must the code read?
Sign in to track lesson progress and earn a certificate.SIGN IN TO SAVE PROGRESS