|
| 1 | +import Kernel, { KernelError } from '@onkernel/sdk'; |
| 2 | +import { OffsetPagination } from '@onkernel/sdk/core/pagination'; |
| 3 | +import type { FinalRequestOptions } from '@onkernel/sdk/internal/request-options'; |
| 4 | + |
| 5 | +const client = new Kernel({ |
| 6 | + apiKey: 'test-api-key', |
| 7 | + fetch: () => Promise.reject(new Error('unexpected request')), |
| 8 | +}); |
| 9 | + |
| 10 | +function pageWith( |
| 11 | + headers: Record<string, string>, |
| 12 | + items: unknown[], |
| 13 | + offset?: number, |
| 14 | +): OffsetPagination<unknown> { |
| 15 | + const options: FinalRequestOptions = { |
| 16 | + method: 'get', |
| 17 | + path: '/proxies', |
| 18 | + query: offset === undefined ? {} : { offset }, |
| 19 | + }; |
| 20 | + return new OffsetPagination(client, new Response('[]', { headers }), items, options); |
| 21 | +} |
| 22 | + |
| 23 | +describe('OffsetPagination', () => { |
| 24 | + test('requests the next page at exactly X-Next-Offset', () => { |
| 25 | + // X-Next-Offset already holds the next page's start. Adding the current |
| 26 | + // page length on top (the old behavior) skipped a full page per iteration. |
| 27 | + const page = pageWith({ 'x-next-offset': '100', 'x-has-more': 'true' }, new Array(100).fill({}), 0); |
| 28 | + expect(page.nextPageRequestOptions()?.query).toEqual({ offset: 100 }); |
| 29 | + }); |
| 30 | + |
| 31 | + test('stops cleanly when the last page omits X-Next-Offset', () => { |
| 32 | + const page = pageWith({ 'x-has-more': 'false' }, new Array(50).fill({}), 100); |
| 33 | + expect(page.nextPageRequestOptions()).toBeNull(); |
| 34 | + expect(page.hasNextPage()).toBe(false); |
| 35 | + }); |
| 36 | + |
| 37 | + test('stops on the X-Next-Offset 0 sentinel even when X-Has-More is true', () => { |
| 38 | + // Call nextPageRequestOptions directly with has_more=true so the has_more |
| 39 | + // gate in hasNextPage() cannot mask it: the 0 offset alone must stop. |
| 40 | + const page = pageWith({ 'x-next-offset': '0', 'x-has-more': 'true' }, new Array(50).fill({}), 100); |
| 41 | + expect(page.nextPageRequestOptions()).toBeNull(); |
| 42 | + }); |
| 43 | + |
| 44 | + test('stops when X-Has-More is false even with a positive X-Next-Offset', () => { |
| 45 | + const page = pageWith({ 'x-next-offset': '200', 'x-has-more': 'false' }, new Array(50).fill({}), 100); |
| 46 | + expect(page.hasNextPage()).toBe(false); |
| 47 | + }); |
| 48 | + |
| 49 | + test('stops on an empty page', () => { |
| 50 | + const page = pageWith({ 'x-next-offset': '300', 'x-has-more': 'true' }, [], 200); |
| 51 | + expect(page.hasNextPage()).toBe(false); |
| 52 | + }); |
| 53 | + |
| 54 | + test('refuses to silently truncate when X-Has-More is true but X-Next-Offset is missing', () => { |
| 55 | + const page = pageWith({ 'x-has-more': 'true' }, new Array(100).fill({})); |
| 56 | + expect(() => page.hasNextPage()).toThrow(KernelError); |
| 57 | + }); |
| 58 | +}); |
0 commit comments