-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.ts
More file actions
55 lines (48 loc) · 1.84 KB
/
Copy pathapi.ts
File metadata and controls
55 lines (48 loc) · 1.84 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
const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:4000';
function getToken(): string | null {
const raw = sessionStorage.getItem('freclean-admin-session');
if (!raw) return null;
try {
return JSON.parse(raw).token ?? null;
} catch {
return null;
}
}
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const token = getToken();
const res = await fetch(`${API_URL}${path}`, {
...options,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...options.headers,
},
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? `Request failed with status ${res.status}`);
}
if (res.status === 204) return undefined as T;
return res.json();
}
export async function apiLogin(email: string, password: string) {
const res = await request<{ data: { token: string; user: { id: string; email: string; role: string } } }>(
'/auth/login',
{ method: 'POST', body: JSON.stringify({ email, password }) },
);
return res.data;
}
export function listResource<T = Record<string, unknown>>(resource: string) {
return request<{ data: T[] }>(`/api/${resource}`).then((r) => r.data);
}
export function createResource<T = Record<string, unknown>>(resource: string, body: unknown) {
return request<{ data: T }>(`/api/${resource}`, { method: 'POST', body: JSON.stringify(body) }).then((r) => r.data);
}
export function updateResource<T = Record<string, unknown>>(resource: string, id: string, body: unknown) {
return request<{ data: T }>(`/api/${resource}/${id}`, { method: 'PATCH', body: JSON.stringify(body) }).then(
(r) => r.data,
);
}
export function deleteResource(resource: string, id: string) {
return request<void>(`/api/${resource}/${id}`, { method: 'DELETE' });
}