-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathapi.ts
More file actions
42 lines (39 loc) · 1 KB
/
api.ts
File metadata and controls
42 lines (39 loc) · 1 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
const API_URL =
process.env.NEXT_PUBLIC_FORESTER_API_URL ?? "/api";
export class ApiError extends Error {
constructor(
message: string,
public status: number,
public serverMessage: string
) {
super(message);
this.name = "ApiError";
}
}
export async function fetchApi<T>(path: string): Promise<T> {
let res: Response;
try {
res = await fetch(`${API_URL}${path}`);
} catch (e) {
// Network error — server not reachable
throw new Error(
`Cannot connect to forester API at ${API_URL}. Make sure the API server is running.`
);
}
if (!res.ok) {
let serverMsg = "";
try {
const body = await res.json();
serverMsg = body.error || JSON.stringify(body);
} catch {
serverMsg = await res.text().catch(() => "Unknown error");
}
throw new ApiError(
`Forester API returned ${res.status}: ${serverMsg}`,
res.status,
serverMsg
);
}
return res.json();
}
export const fetcher = <T>(path: string) => fetchApi<T>(path);