import { useAuth } from '../store/auth' async function request(method: string, url: string, body?: unknown): Promise { const token = useAuth.getState().token const response = await fetch(url, { method, headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}), }, body: body === undefined ? undefined : JSON.stringify(body), }) if (response.status === 401) { useAuth.getState().logout() } if (!response.ok) { const text = await response.text() throw new Error(`${response.status} ${response.statusText}${text ? `: ${text}` : ''}`) } const contentType = response.headers.get('content-type') ?? '' return contentType.includes('application/json') ? ((await response.json()) as T) : (undefined as T) } export const api = { get: (url: string) => request('GET', url), post: (url: string, body?: unknown) => request('POST', url, body), patch: (url: string, body?: unknown) => request('PATCH', url, body), }