Skip to content
Open
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
24 changes: 15 additions & 9 deletions src/lib/seam-paginator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,18 +82,21 @@ export class SeamPaginator<
throw new Error('Cannot paginate a response without a responseKey')
}

const method = this.#request.method

const requestData = {
...(usesParams(method)
? (this.#request.params ?? {})
: ((this.#request.body as Record<string, unknown> | null) ?? {})),
page_cursor: nextPageCursor,
}

const request = new SeamHttpRequest<TResponse, TResponseKey>(this.#parent, {
pathname: this.#request.pathname,
method: this.#request.method,
method,
responseKey,
params:
this.#request.params != null
? { ...this.#request.params, page_cursor: nextPageCursor }
: undefined,
body:
this.#request.body != null
? { ...this.#request.body, page_cursor: nextPageCursor }
: undefined,
params: usesParams(method) ? requestData : undefined,
body: usesParams(method) ? undefined : requestData,
})

const response = await request.fetchResponse()
Expand Down Expand Up @@ -186,6 +189,9 @@ export class SeamPaginator<
}
}

const usesParams = (method: string): boolean =>
['GET', 'DELETE'].includes(method.toUpperCase())

type EnsureReadonlyArray<T> = T extends readonly any[] ? T : never
type EnsureMutableArray<T> = T extends any[] ? T : never
type ElementOfArray<T> =
Expand Down
34 changes: 34 additions & 0 deletions test/seam/connect/seam-paginator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,40 @@ test('SeamPaginator: flatten allows iteration over all devices', async (t) => {

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

test('SeamPaginator: sends the page cursor when the request has no parameters', async (t) => {
const { seed, endpoint } = await getTestServer(t)
const seam = SeamHttp.fromApiKey(seed.seam_apikey1_token, { endpoint })

nock(endpoint)
.get('/devices/list')
.reply(200, {
devices: [{ device_id: 'device-1' }],
pagination: {
has_next_page: true,
next_page_cursor: 'page-cursor-1',
next_page_url: `${endpoint}/devices/list?page_cursor=page-cursor-1`,
},
})
.get('/devices/list')
.query({ page_cursor: 'page-cursor-1', _strict: 'true' })
.reply(200, {
devices: [{ device_id: 'device-2' }],
pagination: {
has_next_page: false,
next_page_cursor: null,
next_page_url: null,
},
})

const pages = seam.createPaginator(seam.devices.list())
const devices = await pages.flattenToArray()

t.deepEqual(
devices.map(({ device_id: deviceId }) => deviceId),
['device-1', 'device-2'],
)
})

test('SeamPaginator: stops iterating when the page cursor repeats', async (t) => {
const { seed, endpoint } = await getTestServer(t)
const seam = SeamHttp.fromApiKey(seed.seam_apikey1_token, { endpoint })
Expand Down
Loading