Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ const pages = seam.createPaginator(
)

for await (const device of pages.flatten()) {
console.log(devices.name)
console.log(device.display_name)
}
```

Expand Down
6 changes: 3 additions & 3 deletions src/lib/seam-paginator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,7 @@ export class SeamPaginator<
/**
* Yields each item across all pages, fetching the next page as needed.
*/
async *flatten(): AsyncGenerator<
EnsureReadonlyArray<TResponse[TResponseKey]>
> {
async *flatten(): AsyncGenerator<ElementOfArray<TResponse[TResponseKey]>> {
let [current, pagination] = await this.firstPage()
for (const item of current) {
yield item
Expand Down Expand Up @@ -174,6 +172,8 @@ export class SeamPaginator<

type EnsureReadonlyArray<T> = T extends readonly any[] ? T : never
type EnsureMutableArray<T> = T extends any[] ? T : never
type ElementOfArray<T> =
T extends ReadonlyArray<infer TElement> ? TElement : never

interface PaginationData {
has_next_page: boolean
Expand Down
17 changes: 12 additions & 5 deletions test/seam/connect/seam-paginator.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import test from 'ava'
import { getTestServer } from 'fixtures/seam/connect/api.js'

import { SeamHttp, SeamPaginator } from '@seamapi/http/connect'
import { type Device, SeamHttp, SeamPaginator } from '@seamapi/http/connect'

test('SeamPaginator: creates a SeamPaginator', async (t) => {
const { seed, endpoint } = await getTestServer(t)
Expand Down Expand Up @@ -80,14 +80,21 @@ test('SeamPaginator: flatten allows iteration over all devices', async (t) => {
const allDevices = await seam.devices.list()
const pages = seam.createPaginator(seam.devices.list({ limit: 1 }))

const devices = []
const deviceIds = []
for await (const device of pages.flatten()) {
devices.push(device)
expectType<Device>(device)

// @ts-expect-error Verify flatten yields single items, not pages.
expectType<Device[]>(device)

deviceIds.push(device.device_id)
}
t.true(devices.length > 1)
t.is(devices.length, allDevices.length)
t.true(deviceIds.length > 1)
t.is(deviceIds.length, allDevices.length)
})

const expectType = <Expected>(_value: Expected): void => {}

test('SeamPaginator: instance allows iteration over all pages', async (t) => {
const { seed, endpoint } = await getTestServer(t)
const seam = SeamHttp.fromApiKey(seed.seam_apikey1_token, { endpoint })
Expand Down
Loading