Repository navigation
Expand file tree
/
Copy pathclient.ts
More file actions
109 lines (93 loc) · 2.57 KB
/
Copy pathclient.ts
File metadata and controls
109 lines (93 loc) · 2.57 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
8000
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* API Client - typed fetch wrapper
*/
const API_BASE = '/api'
interface ApiError {
error: string;
code?: string;
statusCode?: number;
}
export class ApiClientError extends Error {
status: number
code?: string
constructor (message: string, status: number, code?: string) {
super(message)
this.name = 'ApiClientError'
this.status = status
this.code = code
}
}
async function handleResponse<T> (response: Response): Promise<T> {
if (!response.ok) {
// Clear token on 401 Unauthorized - token is invalid
if (response.status === 401) {
localStorage.removeItem('auth_token')
}
const data = (await response.json().catch(() => ({}))) as ApiError
throw new ApiClientError(
data.error || `HTTP ${response.status}`,
response.status,
data.code
)
}
return response.json() as Promise<T>
}
function getHeaders (): HeadersInit {
const headers: HeadersInit = {
'Content-Type': 'application/json',
}
// Add auth token if stored
const token = localStorage.getItem('auth_token')
if (token) {
headers['Authorization'] = `Bearer ${token}`
}
return headers
}
export const api = {
get: async <T>(path: string): Promise<T> => {
const response = await fetch(`${API_BASE}${path}`, {
method: 'GET',
headers: getHeaders(),
})
return handleResponse<T>(response)
},
post: async <T, B = unknown>(path: string, body: B): Promise<T> => {
const response = await fetch(`${API_BASE}${path}`, {
method: 'POST',
headers: getHeaders(),
body: JSON.stringify(body),
})
return handleResponse<T>(response)
},
patch: async <T, B = unknown>(path: string, body: B): Promise<T> => {
const response = await fetch(`${API_BASE}${path}`, {
method: 'PATCH',
headers: getHeaders(),
body: JSON.stringify(body),
})
return handleResponse<T>(response)
},
delete: async <T>(path: string): Promise<T> => {
// Don't set Content-Type for DELETE requests without body
const headers: HeadersInit = {}
const token = localStorage.getItem('auth_token')
if (token) {
headers['Authorization'] = `Bearer ${token}`
}
const response = await fetch(`${API_BASE}${path}`, {
method: 'DELETE',
headers,
})
return handleResponse<T>(response)
},
}
// Auth helpers
export function setAuthToken (token: string) {
localStorage.setItem('auth_token', token)
}
export function clearAuthToken () {
localStorage.removeItem('auth_token')
}
export function getAuthToken (): string | null {
return localStorage.getItem('auth_token')
}