Add the existing application baseline and repository documentation/ignore rules. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
40 lines
1.2 KiB
TypeScript
40 lines
1.2 KiB
TypeScript
const BASE = '/api'
|
|
|
|
function getToken() {
|
|
return localStorage.getItem('token')
|
|
}
|
|
|
|
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
|
|
const token = getToken()
|
|
const res = await fetch(`${BASE}${path}`, {
|
|
...options,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
...options.headers,
|
|
},
|
|
})
|
|
if (res.status === 401) {
|
|
localStorage.removeItem('token')
|
|
localStorage.removeItem('user')
|
|
window.location.href = '/login'
|
|
throw new Error('Session expirée')
|
|
}
|
|
if (!res.ok) {
|
|
const err = await res.json().catch(() => ({ error: res.statusText }))
|
|
throw new Error(err.error || res.statusText)
|
|
}
|
|
if (res.status === 204) return undefined as T
|
|
const json = await res.json()
|
|
return json.data !== undefined ? json.data : json
|
|
}
|
|
|
|
export const api = {
|
|
get: <T>(path: string) => request<T>(path),
|
|
post: <T>(path: string, body?: unknown) =>
|
|
request<T>(path, { method: 'POST', body: body ? JSON.stringify(body) : undefined }),
|
|
put: <T>(path: string, body?: unknown) =>
|
|
request<T>(path, { method: 'PUT', body: body ? JSON.stringify(body) : undefined }),
|
|
delete: <T>(path: string) => request<T>(path, { method: 'DELETE' }),
|
|
}
|