| const base = import.meta.env.VITE_API_URL || '' | |
| export function apiUrl(path: string): string { | |
| if (path.startsWith('http')) return path | |
| const p = path.startsWith('/') ? path : `/${path}` | |
| return base ? `${base.replace(/\/$/, '')}${p}` : p | |
| } | |
| export function getToken(): string | null { | |
| return localStorage.getItem('authToken') | |
| } | |
| export async function apiFetch( | |
| path: string, | |
| options: RequestInit & { auth?: boolean } = {}, | |
| ): Promise<Response> { | |
| const headers = new Headers(options.headers) | |
| if (!headers.has('Content-Type') && options.body && typeof options.body === 'string') { | |
| headers.set('Content-Type', 'application/json') | |
| } | |
| if (options.auth !== false) { | |
| const t = getToken() | |
| if (t) headers.set('Authorization', `Bearer ${t}`) | |
| } | |
| return fetch(apiUrl(path), { ...options, headers }) | |
| } | |