Repository navigation
Expand file tree
/
Copy pathpagination.ts
More file actions
204 lines (169 loc) · 4.9 KB
/
Copy pathpagination.ts
File metadata and controls
204 lines (169 loc) · 4.9 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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { OpenAIError } from './error';
import { FinalRequestOptions } from '../internal/request-options';
import { defaultParseResponse, WithRequestID } from '../internal/parse';
import { APIPromise } from './api-promise';
import { type OpenAI } from '../client';
import { type APIResponseProps } from '../internal/parse';
import { maybeObj } from '../internal/utils/values';
export type PageRequestOptions = Pick<FinalRequestOptions, 'query' | 'headers' | 'body' | 'path' | 'method'>;
export abstract class AbstractPage<Item> implements AsyncIterable<Item> {
#client: OpenAI;
protected options: FinalRequestOptions;
protected response: Response;
protected body: unknown;
constructor(client: OpenAI, response: Response, body: unknown, options: FinalRequestOptions) {
this.#client = client;
this.options = options;
this.response = response;
this.body = body;
}
abstract nextPageRequestOptions(): PageRequestOptions | null;
abstract getPaginatedItems(): Item[];
hasNextPage(): boolean {
const items = this.getPaginatedItems();
if (!items.length) return false;
return this.nextPageRequestOptions() != null;
}
async getNextPage(): Promise<this> {
const nextOptions = this.nextPageRequestOptions();
if (!nextOptions) {
throw new OpenAIError(
'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.',
);
}
return await this.#client.requestAPIList(this.constructor as any, nextOptions);
}
async *iterPages(): AsyncGenerator<this> {
let page: this = this;
yield page;
while (page.hasNextPage()) {
page = await page.getNextPage();
yield page;
}
}
async *[Symbol.asyncIterator](): AsyncGenerator<Item> {
for await (const page of this.iterPages()) {
for (const item of page.getPaginatedItems()) {
yield item;
}
}
}
}
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
export class PagePromise<
PageClass extends AbstractPage<Item>,
Item = ReturnType<PageClass['getPaginatedItems']>[number],
>
extends APIPromise<PageClass>
implements AsyncIterable<Item>
{
constructor(
client: OpenAI,
request: Promise<APIResponseProps>,
Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,
) {
super(
client,
request,
async (client, props) =>
new Page(
client,
props.response,
await defaultParseResponse(client, props),
props.options,
) as WithRequestID<PageClass>,
);
}
/**
* Allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
async *[Symbol.asyncIterator](): AsyncGenerator<Item> {
const page = await this;
for await (const item of page) {
yield item;
}
}
}
export interface PageResponse<Item> {
data: Array<Item>;
object: string;
}
/**
* Note: no pagination actually occurs yet, this is for forwards-compatibility.
*/
export class Page<Item> extends AbstractPage<Item> implements PageResponse<Item> {
data: Array<Item>;
object: string;
constructor(client: OpenAI, response: Response, body: PageResponse<Item>, options: FinalRequestOptions) {
super(client, response, body, options);
this.data = body.data || [];
this.object = body.object;
}
getPaginatedItems(): Item[] {
return this.data ?? [];
}
nextPageRequestOptions(): PageRequestOptions | null {
return null;
}
}
export interface CursorPageResponse<Item> {
data: Array<Item>;
has_more: boolean;
}
export interface CursorPageParams {
after?: string;
limit?: number;
}
export class CursorPage<Item extends { id: string }>
extends AbstractPage<Item>
implements CursorPageResponse<Item>
{
data: Array<Item>;
has_more: boolean;
constructor(
client: OpenAI,
response: Response,
body: CursorPageResponse<Item>,
options: FinalRequestOptions,
) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
}
getPaginatedItems(): Item[] {
return this.data ?? [];
}
override hasNextPage(): boolean {
if (this.has_more === false) {
return false;
}
return super.hasNextPage();
}
nextPageRequestOptions(): PageRequestOptions | null {
const data = this.getPaginatedItems();
const id = data[data.length - 1]?.id;
if (!id) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
after: id,
},
};
}
}