const BASE = "/api/v1"; function getToken(): string | null { return localStorage.getItem("accessToken"); } export function setTokens(accessToken: string, refreshToken: string) { localStorage.setItem("accessToken", accessToken); localStorage.setItem("refreshToken", refreshToken); } export function clearTokens() { localStorage.removeItem("accessToken"); localStorage.removeItem("refreshToken"); } async function request( path: string, options: RequestInit = {} ): Promise { const token = getToken(); const headers: Record = { "Content-Type": "application/json", ...(options.headers as Record), }; if (token) headers["Authorization"] = `Bearer ${token}`; const res = await fetch(`${BASE}${path}`, { ...options, headers }); if (!res.ok) { const body = await res.json().catch(() => ({})); const message = body?.error?.message ?? `HTTP ${res.status}`; throw new Error(message); } return res.json() as Promise; } export const api = { get: (path: string) => request(path), post: (path: string, body: unknown) => request(path, { method: "POST", body: JSON.stringify(body) }), put: (path: string, body: unknown) => request(path, { method: "PUT", body: JSON.stringify(body) }), patch: (path: string, body: unknown) => request(path, { method: "PATCH", body: JSON.stringify(body) }), delete: (path: string) => request(path, { method: "DELETE" }), };