Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
appstore-distribution ▾

xtool.git / Sources / XKit / DeveloperServices / OpenAPI / DeveloperAPIPages.swift

DeveloperAPIPages.swift78 lines · 2.2 KiBRaw
1import DeveloperAPI
2
3/// An `AsyncSequence` that unfolds a paginated DeveloperAPI request.
4///
5/// Some Developer API GET requests are paginated. Each response contains
6/// a `links.next` field that points to the next page. This API allows you to
7/// consume all pages as an `AsyncSequence`. For example, you can
8/// enumerate all devices with
9///
10/// ```swift
11/// let pages = DeveloperAPIPages {
12/// try await client.devicesGetCollection().ok.body.json
13/// } next: {
14/// $0.links.next
15/// }
16/// for try await page in pages {
17/// print(page.data)
18/// }
19/// ```
20public struct DeveloperAPIPages<Page>: AsyncSequence {
21 // inspired by PagedRequest from
22 // https://github.com/AvdLee/appstoreconnect-swift-sdk
23
24 public var request: @Sendable () async throws -> Page
25 public var getNext: @Sendable (Page) -> String?
26
27 public init(
28 request: @escaping @Sendable () async throws -> Page,
29 next getNext: @escaping @Sendable (Page) -> String?
30 ) {
31 self.request = request
32 self.getNext = getNext
33 }
34
35 public func makeAsyncIterator() -> AsyncIterator {
36 AsyncIterator(request: request, getNext: getNext)
37 }
38
39 public struct AsyncIterator: AsyncIteratorProtocol {
40 fileprivate enum State {
41 case initial
42 case hasNext(String)
43 case end
44 }
45
46 fileprivate let request: @Sendable () async throws -> Page
47 fileprivate let getNext: @Sendable (Page) -> String?
48
49 fileprivate var state: State = .initial
50
51 public mutating func next() async throws -> Page? {
52 guard !Task.isCancelled else { return nil }
53
54 let cursor: String?
55
56 switch state {
57 case .initial:
58 cursor = nil
59 case .hasNext(let next):
60 cursor = next
61 case .end:
62 return nil
63 }
64
65 let page = try await DeveloperAPIClient.withNextLink(cursor) {
66 try await request()
67 }
68
69 if let next = getNext(page), next != cursor {
70 state = .hasNext(next)
71 } else {
72 state = .end
73 }
74
75 return page
76 }
77 }
78}