Polski

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.

medium · typescript · javascript · python · csharp · java · go · 20 XP

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:

  1. The native iteration protocol of each language:

    • TypeScript/JavaScript – [Symbol.iterator]() (so for...of, spread and Array.from work);
    • Python – __iter__ (so for, list() and next(iter(...)) work);
    • C# – IEnumerable<T> (so foreach and LINQ work);
    • Java – Iterable<T> with its own Iterator<T>; next() past the end throws NoSuchElementException;
    • Go (1.13, no iterators in the language) – the bufio.Scanner style: for it.Next() { it.Value() }, then it.Err().
  2. 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.
  3. Empty pages are skipped (but their cursor is still followed); an empty result simply has no elements.
  4. Every iteration starts from the first page and has its own state – two iterators over the same collection do not interfere.
  5. Errors – a fetch exception surfaces when that page is reached (in Go: Next() returns false and Err() returns the error). A cursor used a second time in the same iteration ends it with the error Cursor repeated: <cursor> (in Go cursor 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.