Skip to content
intermediate

Review: a paginated fetch that drops a page

This is recall. The code looks finished and is wrong. Find the defect and fix it. You are graded on tests you cannot see.

You asked a model for a helper that fetches every page of a paginated API and returns the records. It produced this, along with tests. The tests pass.

export interface Page<T> {
  items: T[]
  total: number
}

export type FetchPage<T> = (offset: number, limit: number) => Promise<Page<T>>

/**
 * Fetches every page and returns all records in order.
 */
export async function fetchAll<T>(fetchPage: FetchPage<T>, pageSize = 10): Promise<T[]> {
  const first = await fetchPage(0, pageSize)
  const all = [...first.items]

  const pageCount = Math.floor(first.total / pageSize)

  for (let page = 1; page < pageCount; page++) {
    const next = await fetchPage(page * pageSize, pageSize)
    all.push(...next.items)
  }

  return all
}
review — find the defectCtrl+↵ submits · Ctrl+Shift+↵ runsstarter code