Skip to content

Commit

Permalink
fix getAll bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
narthur committed May 6, 2024
1 parent e6b6941 commit 9230303
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 20 deletions.
46 changes: 33 additions & 13 deletions src/factory.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,43 @@ const factory = new Factory();

describe("Factory", () => {
beforeEach(() => {
vi.mocked(client.get)
.mockResolvedValue({
data: {
results: [{}],
next: null,
},
})
.mockResolvedValueOnce({
data: {
results: [{}],
next: "the_next_url",
},
});
vi.mocked(client.get).mockResolvedValue({
data: {
results: [{}],
next: null,
},
});
});

it("gets all", async () => {
vi.mocked(client.get).mockResolvedValueOnce({
data: {
results: [{}],
next: "the_next_url",
},
});
await factory.getMany(1, Row);
expect(client.get).toBeCalledTimes(2);
});

it("treats page as one indexed", async () => {
await factory.getMany(1, Row);
expect(client.get).not.toBeCalledWith(
expect.anything(),
expect.objectContaining({ params: expect.objectContaining({ page: 0 }) }),
);
});

it("includes page with all requests", async () => {
await factory.getMany(1, Row);
expect(client.get).toBeCalledWith(
expect.anything(),
expect.objectContaining({ params: expect.objectContaining({ page: 1 }) }),
);
});

it("returns results", async () => {
const results = await factory.getMany(1, Row);
expect(results).toHaveLength(1);
});
});
14 changes: 7 additions & 7 deletions src/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,16 @@ export class Factory {
options: Record<string, unknown> & { page?: number } = {},
accumulator: R[] = [],
): Promise<R[]> {
const { results, next } = await this.sdk.listRows<R>(tableId, options);
const { page = 1 } = options;
const { results, next } = await this.sdk.listRows<R>(tableId, {
...options,
page,
});
accumulator.push(...results);
if (!next) {
return accumulator;
}
accumulator.push(...results);
return this.getAll(
tableId,
{ ...options, page: (options.page ?? 0) + 1 },
accumulator,
);
return this.getAll(tableId, { ...options, page: page + 1 }, accumulator);
}

private createRows<T extends Row, R extends RowType, F extends Factory>(
Expand Down

0 comments on commit 9230303

Please sign in to comment.