Skip to content

Commit

Permalink
fix: types
Browse files Browse the repository at this point in the history
  • Loading branch information
joscha committed Jul 30, 2024
1 parent c921d4c commit 58027df
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/v1/create_search_iterator_fn.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { PagedResponse } from './paged_response.ts'
import type { PagedRequest } from './paged_request.ts'

// TODO(@joscha): this is a mess, simplify types here whilst preserving the required paged request/response types
export const createSearchIteratorFn = <
FN extends (r: PAGED_REQUEST) => Promise<PAGED_RESPONSE>,
PAGED_REQUEST extends PagedRequest,
Expand All @@ -12,20 +13,25 @@ export const createSearchIteratorFn = <
& string,
SINGLE_RESPONSE = object,
>(searchFn: FN, key: PAYLOAD_KEY) => {
type Single = ReturnType<FN> extends Promise<infer T> ? T : never
type Unwrapped = Single extends { [key in PAYLOAD_KEY]: infer T } ? T
: never
async function* searchIterator(
params: Omit<PAGED_REQUEST, 'page_token'>,
): AsyncGenerator<PAGED_RESPONSE[]> {
params:
& Omit<Parameters<FN>[0], keyof PagedRequest>
& Omit<PAGED_REQUEST, 'page_token'>,
): AsyncGenerator<Unwrapped> {
let page_token: string | undefined = undefined
while (true) {
const response: PAGED_RESPONSE = await searchFn(
// TODO(@joscha): remove cast
(page_token
? { ...params, page_token }
: params) as PAGED_REQUEST,
(page_token ? { ...params, page_token } : params) as Parameters<
FN
>[0],
)

// TODO(@joscha): remove cast
yield response[key] as unknown as PAGED_RESPONSE[]
yield response[key] as Unwrapped

if (response.next_page_token === null) {
// no more pages to fetch
Expand Down

0 comments on commit 58027df

Please sign in to comment.