diff --git a/pagination.test.ts b/pagination.test.ts new file mode 100644 index 0000000..94b331d --- /dev/null +++ b/pagination.test.ts @@ -0,0 +1,64 @@ +import { PageIterator } from "./pagination.ts"; +import { assertEquals } from "std/assert/mod.ts"; + +type MockArtist = { + id: number; + type: "artist"; + name: string; +}; +const totalMockItems = 50; +const mockArtists: MockArtist[] = Array(totalMockItems).fill(0).map(( + _, + i, +) => ({ + id: i, + type: "artist", + name: "Radiohead", +})); + +Deno.test("PageIterator: asyncIterator", async () => { + const pageIterator = new PageIterator((opts) => { + const limit = opts.limit || 20; + const offset = opts.offset || 0; + + return Promise.resolve({ + href: "#", + items: mockArtists.slice(offset, offset + limit), + offset, + limit, + next: offset + limit < totalMockItems ? "http://example.com" : null, + previous: offset > 0 ? "http://example.com" : null, + total: totalMockItems, + }); + }); + + const iter = pageIterator.asyncIterator(); + + for (let i = 0; i < totalMockItems; i++) { + assertEquals(await iter.next(), { done: false, value: mockArtists[i] }); + } + assertEquals(await iter.next(), { + done: true, + value: null, + }); +}); + +Deno.test("PageIterator: collect", async () => { + const pageIterator = new PageIterator((opts) => { + const limit = opts.limit || 20; + const offset = opts.offset || 0; + + return Promise.resolve({ + href: "#", + items: mockArtists.slice(offset, offset + limit), + offset, + limit, + next: offset + limit < totalMockItems ? "http://example.com" : null, + previous: offset > 0 ? "http://example.com" : null, + total: totalMockItems, + }); + }); + + const items = await pageIterator.collect(); + assertEquals(items, mockArtists); +}); diff --git a/pagination.ts b/pagination.ts index 0c45c1b..03e91e7 100644 --- a/pagination.ts +++ b/pagination.ts @@ -82,11 +82,11 @@ export class PageIterator { this.defaults = { ...DEFAULTS, ...defaults }; } - asyncIterator(): AsyncGenerator { + asyncIterator(): AsyncGenerator { return this[Symbol.asyncIterator](); } - async *[Symbol.asyncIterator](): AsyncGenerator { + async *[Symbol.asyncIterator](): AsyncGenerator { let { direction, limit, offset } = this.defaults; while (true) { @@ -96,10 +96,8 @@ export class PageIterator { (direction === "next" && !chunk.next) || (direction === "prev" && !chunk.previous) ) { - const last = chunk.items.pop()!; for (const item of chunk.items) yield item; - - return last; + return null; } for (const item of chunk.items) yield item;