-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathapiClient.ts
More file actions
160 lines (140 loc) · 4.4 KB
/
Copy pathapiClient.ts
File metadata and controls
160 lines (140 loc) · 4.4 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
// 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 type ApiError = {
error: string;
message: string;
requestId?: string;
};
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;
}
}
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 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",
});
}
/**
* 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.
*/
export async function apiFetch<T>(
path: string,
init: ApiFetchInit = {},
): Promise<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 ?? {}),
},
});
if (res.status === 204) { finish(); return undefined as T; }
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 body as T;
} catch (error) {
finish();
if (timeoutError !== undefined) {
throw timeoutError;
}
throw error;
}
}
export function apiGet<T>(path: string, init: ApiFetchInit = {}) {
return apiFetch<T>(path, init);
}
export function apiPost<T>(
path: string,
body: unknown,
init: ApiFetchInit = {},
) {
return apiFetch<T>(path, { ...init, method: "POST", body: JSON.stringify(body) });
}
export const apiPatch = <T>(
path: string,
body: unknown,
init: ApiFetchInit = {},
) =>
apiFetch<T>(path, { ...init, method: "PATCH", body: JSON.stringify(body) });
export const apiDelete = (path: string, init: ApiFetchInit = {}) =>
apiFetch<void>(path, { ...init, method: "DELETE" });