-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.ts
More file actions
66 lines (58 loc) · 1.71 KB
/
api.ts
File metadata and controls
66 lines (58 loc) · 1.71 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
const API_BASE = import.meta.env.VITE_API_BASE ||'https://api.lastpush.xyz/api/v1';// 'http://127.0.0.1:4000/api/v1'//'https://api.lastpush.xyz/api/v1';
const getToken = () => localStorage.getItem('lastpush_token');
type RequestOptions = {
method?: string;
headers?: Record<string, string>;
body?: BodyInit | null;
};
const buildHeaders = (headers?: Record<string, string>) => {
const token = getToken();
return {
...(token ? { Authorization: `Bearer ${token}` } : {}),
...headers,
};
};
const request = async <T>(path: string, options: RequestOptions = {}): Promise<T> => {
const res = await fetch(`${API_BASE}${path}`, {
...options,
headers: buildHeaders(options.headers),
});
if (!res.ok) {
let details = '';
try {
const data = await res.json();
details = data?.error?.message || res.statusText;
} catch {
details = res.statusText;
}
throw new Error(details || 'Request failed');
}
if (res.status === 204) {
return null as T;
}
return res.json() as Promise<T>;
};
export const api = {
get: <T>(path: string) => request<T>(path),
post: <T>(path: string, body?: unknown) =>
request<T>(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: body ? JSON.stringify(body) : undefined,
}),
patch: <T>(path: string, body?: unknown) =>
request<T>(path, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: body ? JSON.stringify(body) : undefined,
}),
del: <T>(path: string) =>
request<T>(path, {
method: 'DELETE',
}),
upload: <T>(path: string, formData: FormData) =>
request<T>(path, {
method: 'POST',
body: formData,
}),
};