All files / src/internal paging.ts

100% Statements 14/14
100% Branches 2/2
100% Functions 5/5
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57                                              19x 19x   19x 19x   40x 17x     23x 21x 21x 21x       19x             8x     2x 4x          
export interface PageSettings {
  continuationToken?: string
}
 
export interface ListOptions extends PageSettings {
  maxPageSize?: number
}
 
/** Iterates items directly or page by page with `byPage`. */
export interface PagedAsyncIterableIterator<T, TPage> extends AsyncIterable<T> {
  byPage: (settings?: PageSettings) => AsyncIterable<TPage>
}
 
export interface Page<T> {
  page: T
  continuationToken?: string
}
 
/** Requests one page per iteration step and stops when a page has no continuation token. */
export function paginate<T>(
  fetchPage: (continuationToken: string | undefined) => Promise<Page<T>>,
  continuationToken?: string,
): AsyncIterableIterator<T> {
  let next = continuationToken
  let done = false
 
  const iterator: AsyncIterableIterator<T> = {
    [Symbol.asyncIterator]: () => iterator,
    next: async () => {
      if (done) {
        return { done: true, value: undefined }
      }
 
      const result = await fetchPage(next)
      next = result.continuationToken
      done = next === undefined
      return { done: false, value: result.page }
    },
  }
 
  return iterator
}
 
/** Adds item iteration on top of a page iterator. */
export function pagedItems<T, TPage extends { value: T[] }>(
  byPage: (settings?: PageSettings) => AsyncIterable<TPage>,
): PagedAsyncIterableIterator<T, TPage> {
  return {
    byPage,
    async *[Symbol.asyncIterator]() {
      for await (const page of byPage()) {
        yield* page.value
      }
    },
  }
}