-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathpagination.ts
More file actions
151 lines (131 loc) · 3.55 KB
/
Copy pathpagination.ts
File metadata and controls
151 lines (131 loc) · 3.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import {
type PaginationCursor,
toPaginationCursor,
} from '@polymarket/bindings';
import { type ResultAsync, unwrap } from '@polymarket/types';
import { z } from 'zod';
import { UserInputError } from './errors';
export const PageSizeSchema = z.number().int().positive();
export type Page<T> = {
items: T;
/**
* Whether another page may be available.
*
* On methods without a server-provided continuation signal, a full page
* reports `true` and the follow-up request returns an empty final page when
* the collection ended exactly on a page boundary.
*/
hasMore: boolean;
nextCursor?: PaginationCursor;
/** Total number of matching items across all pages. Only present when the service reports one. */
totalCount?: number;
};
export type Paginated<T> = AsyncIterable<Page<T>> & {
firstPage(): Promise<Page<T>>;
from(cursor?: PaginationCursor): Paginated<T>;
};
/** @internal */
type OffsetCursorState = {
offset: number;
pageSize: number;
};
/** @internal */
const OffsetCursorStateSchema = z.object({
offset: z.number().int().min(0),
pageSize: PageSizeSchema,
});
/** @internal */
export function paginate<T, TError>(
fetchPage: (cursor?: PaginationCursor) => ResultAsync<Page<T>, TError>,
initialCursor?: PaginationCursor,
emptyItems: T = [] as T,
): Paginated<T> {
function createEmptyPaginator(): Paginated<T> {
return {
async firstPage() {
return {
items: emptyItems,
hasMore: false,
};
},
from() {
return createEmptyPaginator();
},
async *[Symbol.asyncIterator]() {},
};
}
function createPaginator(cursor = initialCursor): Paginated<T> {
return {
async firstPage() {
return unwrap(fetchPage(cursor));
},
from(nextCursor) {
if (nextCursor === undefined) {
return createEmptyPaginator();
}
return createPaginator(nextCursor);
},
async *[Symbol.asyncIterator]() {
let currentCursor = cursor;
while (true) {
const page = await unwrap(fetchPage(currentCursor));
yield page;
if (!page.hasMore) {
return;
}
currentCursor = page.nextCursor;
}
},
};
}
return createPaginator();
}
/** @internal */
export function encodeOffsetCursor(state: OffsetCursorState): PaginationCursor {
return toPaginationCursor(
btoa(JSON.stringify(OffsetCursorStateSchema.parse(state))),
);
}
/** @internal */
export function offsetContinuation(
state: OffsetCursorState,
pageHasMore: boolean,
):
| { hasMore: false; nextCursor?: undefined }
| { hasMore: true; nextCursor: PaginationCursor } {
if (!pageHasMore) {
return { hasMore: false };
}
return {
hasMore: true,
nextCursor: encodeOffsetCursor({
offset: state.offset + state.pageSize,
pageSize: state.pageSize,
}),
};
}
/** @internal */
export function decodeOffsetCursor(
cursor: PaginationCursor | undefined,
pageSize: number,
maxOffset?: number,
): OffsetCursorState {
if (cursor === undefined) {
return {
offset: 0,
pageSize,
};
}
let state: OffsetCursorState;
try {
state = OffsetCursorStateSchema.parse(JSON.parse(atob(cursor)));
} catch (error) {
throw new UserInputError('Invalid pagination cursor', { cause: error });
}
if (maxOffset !== undefined && state.offset > maxOffset) {
throw new UserInputError(
`Pagination cannot continue past the endpoint maximum offset of ${maxOffset}; narrow the query before continuing`,
);
}
return state;
}