Repository navigation
Expand file tree
/
Copy pathapi.ts
More file actions
74 lines (72 loc) · 2.07 KB
/
Copy pathapi.ts
File metadata and controls
74 lines (72 loc) · 2.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
import { errorCopy } from "./errorMessages";
export class ApiError extends Error {
constructor(
public status: number,
message: string,
public code?: string,
public errorId?: string,
) {
super(message);
this.name = "ApiError";
}
}
/** Same-origin only. Credentials live in React memory, never in URLs or browser storage. */
export async function request<T>(
token: string,
path: string,
data?: unknown,
signal?: AbortSignal,
): Promise<T> {
if (!path.startsWith("/api/") || path.includes("://"))
throw new Error("Invalid API path");
const response = await fetch(path, {
method: data === undefined ? "GET" : "POST",
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
...(data === undefined ? {} : { "Content-Type": "application/json" }),
},
body: data === undefined ? undefined : JSON.stringify(data),
credentials: "omit",
cache: "no-store",
redirect: "error",
signal,
});
let result: unknown;
try {
result = await response.json();
} catch {
throw new ApiError(response.status, "Invalid server response");
}
if (!response.ok) {
const message =
typeof result === "object" &&
result !== null &&
"error" in result &&
typeof result.error === "string"
? result.error
: `HTTP ${response.status}`;
const details = result as { code?: string; error_id?: string };
throw new ApiError(
response.status,
details.code && errorCopy[details.code]
? `error_code:${details.code}`
: details.code === "internal_error"
? `internal_error:${details.error_id ?? ""}`
: message,
details.code,
details.error_id,
);
}
return result as T;
}
export function listOf<T>(items: T[] | Record<string, T> | undefined): T[] {
return Array.isArray(items) ? items : Object.values(items ?? {});
}
export function remainingPercent(
value: number | undefined | null,
): number | null {
return typeof value === "number" && Number.isFinite(value)
? Math.min(100, Math.max(0, value))
: null;
}