import type { ApiError } from './types' export class ApiRequestError extends Error { status: number payload: ApiError | null constructor(message: string, status: number, payload: ApiError | null = null) { super(message) this.name = 'ApiRequestError' this.status = status this.payload = payload } } export async function request(path: string, init: RequestInit = {}): Promise { const response = await fetch(path, { credentials: 'include', ...init, headers: { ...(init.body && !(init.body instanceof FormData) ? { 'content-type': 'application/json' } : {}), ...(init.headers || {}), }, }) const contentType = response.headers.get('content-type') || '' const payload = contentType.includes('json') ? await response.json().catch(() => null) : null if (!response.ok) { const error = payload as ApiError | null throw new ApiRequestError( error?.error || error?.message || error?.detail || response.statusText, response.status, error, ) } return (payload ?? (await response.text())) as T } export function get(path: string) { return request(path) } export function post(path: string, body?: unknown) { return request(path, { method: 'POST', ...(body === undefined ? {} : { body: body instanceof FormData ? body : JSON.stringify(body) }), }) } export function put(path: string, body: unknown) { return request(path, { method: 'PUT', body: JSON.stringify(body) }) } export function del(path: string) { return request(path, { method: 'DELETE' }) }