Skip to content

Pagination and Batch

Husnain Ali edited this page Sep 27, 2026 · 2 revisions

Pagination and Batch

struct ListUsers: PaginatedEndpoint {
    typealias Response = [User]
    var page = 1
    var path: String { "/users" }
    var queryParameters: QueryParameters? { ["_page": .int(page), "_limit": .int(20)] }

    func items(from response: [User]) -> [User] { response }
    func nextPage(after response: [User]) -> Self? {
        guard !response.isEmpty else { return nil }
        var next = self; next.page += 1; return next
    }
}

for try await pageOfUsers in client.paginate(ListUsers()) { ... }   // one array per page
let everyone = try await client.collectAll(ListUsers(), max: 500)   // flattened, capped

nextPage(after:) gives the endpoint full control of the scheme (page number, cursor, Link: header). paginate honors task cancellation and caps at maxPages (default 1000). paginate ends quietly at the cap, but collectAll throws instead, so a partial array is never mistaken for the whole list; raise the cap with collectAll(_:max:maxPages:).

Parallel requests

let (profile, feed) = try await client.zip(GetProfile(), GetFeed())
let items = await client.batch(ids.map { GetItem(id: $0) })   // [Result<Item, NetworkError>]

Clone this wiki locally