-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathapiClient.ts
More file actions
253 lines (217 loc) · 7.07 KB
/
Copy pathapiClient.ts
File metadata and controls
253 lines (217 loc) · 7.07 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
// Lightweight wrapper around fetch() for the AgentPay backend API.
// Centralises base URL resolution and error handling so call sites stay
// small.
import { resolveApiBase } from "./resolveApiBase";
// Resolved at module load time so any misconfiguration surfaces during boot
// rather than at the first fetch.
const API_BASE = resolveApiBase();
const DEFAULT_API_TIMEOUT_MS = 10_000;
export const RATE_LIMIT_WARNING_THRESHOLD = 10;
export type ApiError = {
error: string;
message: string;
requestId?: string;
};
export type RateLimitInfo = {
remaining: number | null;
limit: number | null;
resetAt: number | null;
retryAfterMs: number | null;
};
export type ApiResult<T> = {
data: T;
rateLimit: RateLimitInfo;
};
export type ApiFetchInit = RequestInit & {
/** Request timeout in milliseconds. Pass 0 or a negative value to disable. */
timeoutMs?: number;
};
export class ApiTimeoutError extends Error {
timeoutMs: number;
constructor(timeoutMs: number) {
super(`request timed out after ${timeoutMs}ms`);
this.name = "ApiTimeoutError";
this.timeoutMs = timeoutMs;
}
}
export class ApiRateLimitedError extends Error {
retryAfterMs: number;
constructor(retryAfterMs: number) {
const seconds = Math.ceil(retryAfterMs / 1000);
super(`Rate limited. Retry after ${seconds}s`);
this.name = "ApiRateLimitedError";
this.retryAfterMs = retryAfterMs;
}
}
function shouldUseTimeout(timeoutMs: number) {
return Number.isFinite(timeoutMs) && timeoutMs > 0;
}
async function readJson(res: Response): Promise<unknown> {
const parsed = await res.json();
return parsed === null ? undefined : parsed;
}
function parseRateLimit(headers: Headers | undefined): RateLimitInfo {
const rawRemaining = headers?.get("X-RateLimit-Remaining");
const rawLimit = headers?.get("X-RateLimit-Limit");
const rawReset = headers?.get("X-RateLimit-Reset");
const rawRetryAfter = headers?.get("Retry-After");
const remaining = rawRemaining != null ? Number(rawRemaining) : null;
const limit = rawLimit != null ? Number(rawLimit) : null;
const resetAt = rawReset != null ? Number(rawReset) : null;
const retryAfterMs =
rawRetryAfter != null ? Number(rawRetryAfter) * 1000 : null;
return { remaining, limit, resetAt, retryAfterMs };
}
function warnLowQuota(rateLimit: RateLimitInfo): void {
if (
rateLimit.remaining !== null &&
rateLimit.remaining > 0 &&
rateLimit.remaining <= RATE_LIMIT_WARNING_THRESHOLD
) {
console.warn(
`API rate-limit near exhaustion: ${rateLimit.remaining} calls remaining`,
);
}
}
function createHttpError(status: number, body: unknown, statusText = "") {
const apiError =
body && typeof body === "object" ? (body as Partial<ApiError>) : undefined;
const message =
typeof apiError?.message === "string" && apiError.message.length > 0
? apiError.message
: statusText.trim().length > 0
? statusText
: "Request failed";
const err = new Error(message);
return Object.assign(err, apiError ?? {}, {
error:
typeof apiError?.error === "string" && apiError.error.length > 0
? apiError.error
: "http_error",
});
}
const pendingGets = new Map<string, Promise<unknown>>();
function resolveUrl(path: string): string {
return `${API_BASE}${path}`;
}
/**
* Fetch JSON from the AgentPay API.
*
* `timeoutMs` defaults to 10 seconds. A caller-provided `signal` is composed
* with the internal timeout signal, so whichever aborts first wins. Timers and
* caller abort listeners are always cleared after the request settles.
*
* The returned `ApiResult` includes the response body as `data` and
* rate-limit header values as `rateLimit`. If the backend returns HTTP 429
* the call throws `ApiRateLimitedError` instead of a generic error.
*/
export async function apiFetch<T>(
path: string,
init: ApiFetchInit = {},
): Promise<ApiResult<T>> {
const { timeoutMs, signal: callerSignal, headers, ...restInit } = init;
const effectiveTimeoutMs = timeoutMs ?? DEFAULT_API_TIMEOUT_MS;
const controller = new AbortController();
let timeoutId: ReturnType<typeof setTimeout> | undefined;
let timeoutError: ApiTimeoutError | undefined;
const abortFromCaller = () => {
controller.abort(callerSignal!.reason);
};
if (callerSignal?.aborted) {
abortFromCaller();
} else {
callerSignal?.addEventListener("abort", abortFromCaller, { once: true });
}
if (shouldUseTimeout(effectiveTimeoutMs) && !controller.signal.aborted) {
timeoutId = setTimeout(() => {
timeoutError = new ApiTimeoutError(effectiveTimeoutMs);
controller.abort(timeoutError);
}, effectiveTimeoutMs);
}
function finish() {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
if (callerSignal != null) {
callerSignal.removeEventListener("abort", abortFromCaller);
}
}
try {
const res = await fetch(`${API_BASE}${path}`, {
...restInit,
signal: controller.signal,
headers: {
"Content-Type": "application/json",
...(headers ?? {}),
},
});
const rateLimit = parseRateLimit(res.headers);
if (res.status === 429) {
finish();
const retryAfter = rateLimit.retryAfterMs ?? 0;
if (retryAfter > 0) {
warnLowQuota(rateLimit);
}
throw new ApiRateLimitedError(retryAfter);
}
warnLowQuota(rateLimit);
if (res.status === 204) {
finish();
return { data: undefined as T, rateLimit };
}
let body: T | ApiError | undefined;
try {
body = (await readJson(res)) as T | ApiError | undefined;
} catch {
if (!res.ok) {
finish();
throw createHttpError(res.status, undefined, res.statusText);
}
finish();
throw new Error("Response body was not valid JSON");
}
if (!res.ok) {
finish();
throw createHttpError(res.status, body, res.statusText);
}
finish();
return { data: body as T, rateLimit };
} catch (error) {
finish();
if (timeoutError !== undefined) {
throw timeoutError;
}
throw error;
}
}
export function apiGet<T>(path: string, init: ApiFetchInit = {}): Promise<T> {
const url = resolveUrl(path);
const existing = pendingGets.get(url);
if (existing) {
return (existing as Promise<ApiResult<T>>).then((r) => r.data);
}
const { signal: callerSignal, ...sharedInit } = init;
void callerSignal;
const promise = apiFetch<T>(path, sharedInit).finally(() => {
if (pendingGets.get(url) === promise) {
pendingGets.delete(url);
}
});
pendingGets.set(url, promise);
return promise.then((r) => r.data);
}
export function apiPost<T>(
path: string,
body: unknown,
init: ApiFetchInit = {},
) {
return apiFetch<T>(path, { ...init, method: "POST", body: JSON.stringify(body) }).then((r) => r.data);
}
export const apiPatch = <T>(
path: string,
body: unknown,
init: ApiFetchInit = {},
) =>
apiFetch<T>(path, { ...init, method: "PATCH", body: JSON.stringify(body) }).then((r) => r.data);
export const apiDelete = (path: string, init: ApiFetchInit = {}) =>
apiFetch<void>(path, { ...init, method: "DELETE" }).then((r) => r.data);