Lazy iterator over a paged API
Orders from an API that returns pages with a cursor, exposed as one collection – lazy page fetching, skipping empty pages, protection against a looping cursor and the native iteration protocol of every language.
The payment platform's API returns orders in pages: { items, nextCursor }, and the next page is fetched by passing the cursor from the previous one. Today every report repeats the same while (cursor) loop with manual list concatenation – and every now and then someone fetches all 400 pages just to show the first ten rows. Iterator hides how a collection is traversed: client code writes an ordinary for, and only the iterator knows about pages.
Task
The collection (PagedCollection, in Go PageIterator) receives a fetchPage(cursor) function that returns the first page for an empty cursor (null/None/""). Requirements:
The native iteration protocol of each language:
- TypeScript/JavaScript –
[Symbol.iterator]()(sofor...of, spread andArray.fromwork); - Python –
__iter__(sofor,list()andnext(iter(...))work); - C# –
IEnumerable<T>(soforeachand LINQ work); - Java –
Iterable<T>with its ownIterator<T>;next()past the end throwsNoSuchElementException; - Go (1.13, no iterators in the language) – the
bufio.Scannerstyle:for it.Next() { it.Value() }, thenit.Err().
- TypeScript/JavaScript –
- Laziness – creating an iterator fetches nothing; the first page is fetched with the first element, the next one only when the current page runs out. Breaking out of the loop after three elements fetches no further pages.
- Empty pages are skipped (but their cursor is still followed); an empty result simply has no elements.
- Every iteration starts from the first page and has its own state – two iterators over the same collection do not interfere.
- Errors – a fetch exception surfaces when that page is reached (in Go:
Next()returnsfalseandErr()returns the error). A cursor used a second time in the same iteration ends it with the errorCursor repeated: <cursor>(in Gocursor repeated: <cursor>), raised when the cursor is about to be used – elements from earlier pages have already been delivered.
Topics: Iterator
Related articles
- Iterator: walking a collection without looking inside
The Iterator pattern through orders from a delivery app fetched page by page: the loop in the report knows nothing about pagination, and pages load lazily, only when needed. Generators, yield and iter.Seq in five languages.