Skip to content

Commit

Permalink
Merge pull request #5 from voiceflow/pedro/add-option-to-exhaust-list…
Browse files Browse the repository at this point in the history
…-calls/PL-000

feat: add new exhaust option to list calls (PL-000)
  • Loading branch information
pmvrmc committed Oct 16, 2023
2 parents b168916 + 50da95f commit 88aaef0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 7 deletions.
41 changes: 34 additions & 7 deletions src/chargebee-resource.class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ import type { RequestWrapper } from "chargebee-typescript/lib/request_wrapper";
import type { ListResult } from "chargebee-typescript/lib/list_result";
import type { Result } from "chargebee-typescript/lib/result";

import type {
ResourceResult,
ResultMethodName,
ProcessWaitMethodName,
ListResultMethodName,
ResolveResultReturn,
import {
type ResourceResult,
type ResultMethodName,
type ProcessWaitMethodName,
type ListResultMethodName,
type ResolveResultReturn,
isListOffsetOption,
} from "./chargebee-resource.types";

export class ChargebeeResource {
Expand Down Expand Up @@ -69,7 +70,7 @@ export class ChargebeeResource {
methodName
] as MethodDefinition;

return async (...args: Parameters<MethodDefinition>) => {
const method = async (...args: Parameters<MethodDefinition>) => {
return functionDef(...args)
.request()
.then((listResult) => {
Expand All @@ -80,6 +81,32 @@ export class ChargebeeResource {
};
});
};

const iterate = async function* (...args: Parameters<typeof method>) {
let offset = args.find(isListOffsetOption)?.offset;

do {
const forwardArgs = args.map((arg) =>
Object.assign(arg, { offset }),
) as Parameters<typeof functionDef>;

const listResult = await method(...forwardArgs);
yield* listResult.items;
offset = listResult.nextOffset;
} while (offset);
};

const all = async (...args: Parameters<typeof method>) => {
const items: ResolveResultReturn<TReturning>[] = [];

for await (const result of iterate(...args)) {
items.push(result);
}

return items;
};

return Object.assign(method, { all, iterate });
}

private resolveResult =
Expand Down
3 changes: 3 additions & 0 deletions src/chargebee-resource.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,6 @@ export type ResolveResultReturn<T extends ResourceResult> = {
: Result[K]
: never;
};

export const isListOffsetOption = (arg: unknown): arg is { offset: string } =>
typeof arg === "object" && "offset" in arg && typeof arg.offset === "string";

0 comments on commit 88aaef0

Please sign in to comment.