http.ts
982 Bytes
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
export class HttpError extends Error {
status: number;
payload: unknown;
constructor(status: number, message: string, payload: unknown) {
super(message);
this.status = status;
this.payload = payload;
}
}
const API_BASE = "/api";
export async function requestJson<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${API_BASE}${path}`, {
...init,
headers: {
"Content-Type": "application/json",
...(init?.headers ?? {}),
},
});
const text = await res.text();
const payload = text ? safeJsonParse(text) : null;
if (!res.ok) {
const message =
typeof payload === "object" && payload && "error" in (payload as any)
? String((payload as any).error)
: `HTTP ${res.status}`;
throw new HttpError(res.status, message, payload);
}
return payload as T;
}
function safeJsonParse(text: string): unknown {
try {
return JSON.parse(text);
} catch {
return text;
}
}