this repo has no description
1const TOKEN_KEY = 'ayos_token';
2
3function getToken(): string | null {
4 return localStorage.getItem(TOKEN_KEY);
5}
6
7async function request<T>(
8 method: string,
9 path: string,
10 body?: unknown,
11): Promise<T> {
12 const headers: Record<string, string> = {
13 'Content-Type': 'application/json',
14 };
15
16 const token = getToken();
17 if (token) {
18 headers['Authorization'] = `Bearer ${token}`;
19 }
20
21 const response = await fetch(path, {
22 method,
23 headers,
24 body: body != null ? JSON.stringify(body) : undefined,
25 });
26
27 if (!response.ok) {
28 let message = `Request failed: ${response.status}`;
29 try {
30 const errorData = await response.json();
31 if (errorData.error) {
32 message = errorData.error;
33 } else if (errorData.message) {
34 message = errorData.message;
35 }
36 } catch {
37 // ignore JSON parse errors
38 }
39 throw new Error(message);
40 }
41
42 if (response.status === 204) {
43 return undefined as T;
44 }
45
46 return response.json() as Promise<T>;
47}
48
49export const apiClient = {
50 get<T>(path: string): Promise<T> {
51 return request<T>('GET', path);
52 },
53
54 post<T>(path: string, body?: unknown): Promise<T> {
55 return request<T>('POST', path, body);
56 },
57
58 put<T>(path: string, body?: unknown): Promise<T> {
59 return request<T>('PUT', path, body);
60 },
61
62 delete<T>(path: string): Promise<T> {
63 return request<T>('DELETE', path);
64 },
65};