about summary refs log tree commit diff
path: root/src/lib/async/accumulate.ts
blob: 99226418eda10df4e3462cfda75130eb31c723f0 (plain) (blame)
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
export interface AccumulateResponse<T> {
  cursor?: string
  items: T[]
}

export type AccumulateFetchFn<T> = (
  cursor: string | undefined,
) => Promise<AccumulateResponse<T>>

export async function accumulate<T>(
  fn: AccumulateFetchFn<T>,
  pageLimit = 100,
): Promise<T[]> {
  let cursor: string | undefined
  let acc: T[] = []
  for (let i = 0; i < pageLimit; i++) {
    const res = await fn(cursor)
    cursor = res.cursor
    acc = acc.concat(res.items)
    if (!cursor) {
      break
    }
  }
  return acc
}