-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathclient.ts
More file actions
324 lines (287 loc) · 10.3 KB
/
Copy pathclient.ts
File metadata and controls
324 lines (287 loc) · 10.3 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/**
* Main HTTP client for the CommonGrants API.
*/
import { type ClientConfig, type ResolvedConfig, resolveConfig } from "./config";
import { Auth, buildAuthHeaders, type AuthMethod } from "./auth";
import { Opportunities } from "./opportunities";
import type { Paginated } from "../types";
// =============================================================================
// Options interfaces
// =============================================================================
/** Options for GET requests */
export interface GetOptions {
/** Query parameters to append to the URL */
params?: Record<string, string | number | boolean>;
/** Abort signal for cancellation */
signal?: AbortSignal;
}
/** Options for POST requests */
export interface PostOptions {
/** Abort signal for cancellation */
signal?: AbortSignal;
}
/** Options for the fetchMany auto-pagination method. */
export interface FetchManyOptions<T = unknown> {
/** Starting page number (default: 1) */
page?: number;
/** Items per page (uses client default if not specified) */
pageSize?: number;
/** Maximum total items to fetch (uses client default if not specified) */
maxItems?: number;
/** Abort signal for cancellation */
signal?: AbortSignal;
/** HTTP method (default: "GET") */
method?: "GET" | "POST";
/** Request body for POST requests (pagination will be merged in) */
body?: Record<string, unknown>;
/** Schema to parse/validate each item (any object with a `.parse()` method, e.g. a Zod schema) */
schema?: { parse: (data: unknown) => T };
}
// =============================================================================
// Client class
// =============================================================================
/**
* HTTP client for interacting with the CommonGrants API.
*
* @example
* ```ts
* import { Client, Auth } from "@common-grants/sdk/client";
*
* const client = new Client({
* baseUrl: "https://api.example.org",
* auth: Auth.bearer("your-token"),
* });
*
* // Get an opportunity
* const opp = await client.opportunities.get("opp-123");
* console.log(opp.title);
*
* // List opportunities
* const list = await client.opportunities.list({ page: 1 });
* ```
*/
export class Client {
private readonly config: ResolvedConfig;
private readonly auth: AuthMethod;
/** Opportunities resource namespace */
public readonly opportunities: Opportunities;
// =============================================================================
// Client constructor
// =============================================================================
constructor(options: ClientConfig & { auth?: AuthMethod }) {
this.config = resolveConfig(options);
this.auth = options.auth ?? Auth.none();
// Initialize resource namespaces
this.opportunities = new Opportunities(this);
}
// =============================================================================
// Client.fetch - raw fetch with auth
// =============================================================================
/**
* Makes an authenticated fetch request to the API.
* This is the lowest-level method - use `get()` or `post()` for convenience.
*
* @param path - API path (will be appended to baseUrl)
* @param init - Fetch init options
* @returns Fetch Response
*
* @example
* ```ts
* const response = await client.fetch("/common-grants/opportunities", {
* method: "DELETE",
* });
* ```
*/
async fetch(path: string, init?: RequestInit): Promise<Response> {
const url = this.url(path);
const headers = {
"Content-Type": "application/json",
...buildAuthHeaders(this.auth),
...init?.headers,
};
const response = await fetch(url, {
...init,
headers,
signal: init?.signal ?? AbortSignal.timeout(this.config.timeout),
});
return response;
}
// =============================================================================
// Client.get - GET request helper
// =============================================================================
/**
* Makes an authenticated GET request to the API.
*
* @param path - API path (will be appended to baseUrl)
* @param options - GET request options
* @returns Fetch Response
*
* @example
* ```ts
* const response = await client.get("/common-grants/opportunities", {
* params: { page: 1, pageSize: 10 }
* });
* const data = await response.json();
* ```
*/
async get(path: string, options?: GetOptions): Promise<Response> {
let fullPath = path;
// Append query params if provided
if (options?.params && Object.keys(options.params).length > 0) {
const url = new URL(this.url(path));
for (const [key, value] of Object.entries(options.params)) {
url.searchParams.set(key, String(value));
}
fullPath = url.pathname + url.search;
}
return this.fetch(fullPath, {
method: "GET",
signal: options?.signal,
});
}
// =============================================================================
// Client.post - POST request helper
// =============================================================================
/**
* Makes an authenticated POST request to the API.
*
* @param path - API path (will be appended to baseUrl)
* @param body - Request body (will be JSON stringified)
* @param options - POST request options
* @returns Fetch Response
*
* @example
* ```ts
* const response = await client.post("/common-grants/opportunities/search", {
* filters: { status: "open" },
* pagination: { page: 1, pageSize: 10 }
* });
* const data = await response.json();
* ```
*/
async post(path: string, body: unknown, options?: PostOptions): Promise<Response> {
return this.fetch(path, {
method: "POST",
body: JSON.stringify(body),
signal: options?.signal,
});
}
// =============================================================================
// Client.fetchMany - auto-pagination
// =============================================================================
/**
* Fetches all items from a paginated endpoint with auto-pagination.
*
* @param path - API path (will be appended to baseUrl)
* @param options - Pagination options
* @returns All items aggregated from paginated responses
*
* @example
* ```ts
* // GET with auto-pagination
* const result = await client.fetchMany<Opportunity>("/common-grants/opportunities");
*
* // POST with auto-pagination (for search endpoints)
* const searched = await client.fetchMany<Opportunity>("/common-grants/opportunities/search", {
* method: "POST",
* body: { filters: { status: "open" } }
* });
* ```
*/
async fetchMany<T>(path: string, options?: FetchManyOptions<T>): Promise<Paginated<T>> {
// Set defaults.
const pageSize = options?.pageSize ?? this.config.pageSize;
const maxItems = options?.maxItems ?? this.config.maxItems;
const method = options?.method ?? "GET";
const startPage = options?.page ?? 1;
// Fetch first page so we always have firstPageJson.
const firstResult = await this.fetchOnePage<T>(path, method, startPage, pageSize, options);
const firstPageJson = firstResult.json;
const allItems: T[] = [...firstResult.items.slice(0, maxItems)];
// Fetch remaining pages, up to maxItems.
let currentPage = startPage + 1;
while (allItems.length < maxItems && !firstResult.isLastPage) {
const result = await this.fetchOnePage<T>(path, method, currentPage, pageSize, options);
// Add items up to maxItems limit.
const remainingCapacity = maxItems - allItems.length;
allItems.push(...result.items.slice(0, remainingCapacity));
// Stop if we've fetched all available items.
if (result.isLastPage || allItems.length >= maxItems) break;
currentPage++;
}
// Return the results.
return {
...firstPageJson,
items: allItems,
paginationInfo: {
...firstPageJson.paginationInfo,
page: 1,
pageSize: allItems.length,
},
} as Paginated<T>;
}
// =============================================================================
// Private helper functions
// =============================================================================
/**
* Fetches a single page from a paginated endpoint and returns the parsed
* items plus metadata needed to drive fetchMany's aggregation loop.
*/
private async fetchOnePage<T>(
path: string,
method: "GET" | "POST",
currentPage: number,
pageSize: number,
options?: FetchManyOptions<T>
): Promise<{
json: Paginated<unknown>;
items: T[];
isLastPage: boolean;
totalPages: number | undefined;
}> {
let response: Response;
// Fetch the page.
if (method === "POST") {
// Add pagination to the request body if it's a POST request.
const requestBody = {
...options?.body,
pagination: { page: currentPage, pageSize },
};
response = await this.post(path, requestBody, { signal: options?.signal });
} else {
// Add pagination to the request params if it's a GET request.
response = await this.get(path, {
params: { page: currentPage, pageSize },
signal: options?.signal,
});
}
// Throw an error if the response is not OK.
if (!response.ok) {
throw new Error(`Failed to fetch ${path}: ${response.status} ${response.statusText}`);
}
// Parse/validate items if schema is provided
const json = (await response.json()) as Paginated<unknown>;
const { items: rawItems, paginationInfo } = json;
const items: T[] = options?.schema
? rawItems.map(item => options.schema!.parse(item))
: (rawItems as T[]);
// Determine if this is the last page.
const totalPages = paginationInfo.totalPages ?? undefined;
const isLastPage =
items.length < pageSize ||
(totalPages !== undefined && currentPage >= totalPages) ||
items.length === 0;
// Return the results.
return { json, items, isLastPage, totalPages };
}
/** Constructs the full URL for an API path. */
private url(path: string): string {
// Ensure path starts with /
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
return `${this.config.baseUrl}${normalizedPath}`;
}
/** Gets the resolved client configuration. */
getConfig(): ResolvedConfig {
return { ...this.config };
}
}