Skip to content

Commit

Permalink
fix: correct resource return types
Browse files Browse the repository at this point in the history
  • Loading branch information
trs committed Aug 31, 2023
1 parent 549ebec commit 24450d8
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions src/resources/abstract-resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,18 @@ type ResultConstructor<K extends keyof Result> = {
new (...args: unknown[]): Result[K];
};

type ResolveResult<T extends { [K in keyof Result]?: ResultConstructor<K> }> = {
[K in keyof T]: K extends keyof Result ? Result[K] : never;
};

export abstract class ChargebeeResource {
constructor(protected readonly chargebee: ChargeBee) {}

private resolveGetters =
<TResult extends { [K in keyof Result]?: ResultConstructor<K> }>(
result: TResult,
) =>
(value: Result): TResult => {
(value: Result) => {
const descriptors = Object.getOwnPropertyDescriptors(
value.constructor.prototype,
);
Expand All @@ -85,7 +89,7 @@ export abstract class ChargebeeResource {
properties
.filter((key) => Object.keys(result).includes(key))
.map((key) => [key, value[key]]),
) as TResult;
) as ResolveResult<TResult>;
};

protected request<
Expand All @@ -102,7 +106,7 @@ export abstract class ChargebeeResource {
) =>
async (
...args: Parameters<ChargeBeeResultFunction<TResource, TMethod>>
): Promise<TResult> => {
): Promise<ResolveResult<TResult>> => {
return this.chargebee[resourceProp][methodProp as unknown as TMethod](
...args,
)
Expand All @@ -126,7 +130,7 @@ export abstract class ChargebeeResource {
) =>
async (
...args: Parameters<ChargeBeeListResultFunction<TResource, TMethod>>
): Promise<TResult[]> => {
): Promise<ResolveResult<TResult>[]> => {
const request = (offset: string | undefined): Promise<ListResult> => {
const forwardArgs = args.map((arg) =>
Object.assign(arg, { offset }),
Expand All @@ -147,15 +151,15 @@ export abstract class ChargebeeResource {
? args[0]?.offset
: undefined;

const items: TResult[] = [];
const items: Result[] = [];

do {
const response = await request(offset);
items.push(...response.list.map(this.resolveGetters(result)));
items.push(...response.list);
offset = response.next_offset;
} while (offset);

return items;
return items.map(this.resolveGetters(result));
},
};
}
Expand All @@ -174,7 +178,7 @@ export abstract class ChargebeeResource {
) =>
async (
...args: Parameters<ChargeBeeResultFunction<TResource, TMethod>>
): Promise<TResult> => {
): Promise<ResolveResult<TResult>> => {
return await this.chargebee[resourceProp][
methodProp as unknown as TMethod
](...args)
Expand Down

0 comments on commit 24450d8

Please sign in to comment.