import type { ApiResponse } from './types' const TOKEN_KEY = 'gen2d_token' export function getToken(): string | null { return localStorage.getItem(TOKEN_KEY) } export function setToken(token: string): void { localStorage.setItem(TOKEN_KEY, token) } export function clearToken(): void { localStorage.removeItem(TOKEN_KEY) } export class ApiError extends Error { code: number constructor(code: number, message: string) { super(message) this.code = code } } async function request(url: 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(url, { ...options, headers, credentials: 'include', }) const json: ApiResponse = await res.json() if (json.code !== 0) { throw new ApiError(json.code, json.message) } return json.data } export function get(url: string): Promise { return request(url) } export function post(url: string, body?: unknown): Promise { return request(url, { method: 'POST', body: body ? JSON.stringify(body) : undefined, }) } export function put(url: string, body?: unknown): Promise { return request(url, { method: 'PUT', body: body ? JSON.stringify(body) : undefined, }) }