export class ApiError extends Error { constructor( public readonly status: number, message: string, ) { super(message) } } type UnauthorizedHandler = () => void let onUnauthorized: UnauthorizedHandler | null = null /** Called on 401 responses (except for the login request itself). */ export function setUnauthorizedHandler(handler: UnauthorizedHandler): void { onUnauthorized = handler } function readCookie(name: string): string | null { const match = document.cookie.split('; ').find((c) => c.startsWith(`${name}=`)) return match ? decodeURIComponent(match.slice(name.length + 1)) : null } async function errorMessage(response: Response): Promise { try { const data: unknown = await response.json() if (data && typeof data === 'object' && 'detail' in data) { const detail = (data as { detail: unknown }).detail if (typeof detail === 'string') return detail if (Array.isArray(detail)) return 'Ungültige Eingabe.' } } catch { // body is not JSON } return `${response.status} ${response.statusText}` } export async function apiRequest(method: string, path: string, body?: unknown): Promise { const headers: Record = { Accept: 'application/json' } if (body !== undefined) headers['Content-Type'] = 'application/json' if (method !== 'GET') { const csrf = readCookie('lc_csrf') if (csrf) headers['X-CSRF-Token'] = csrf } const response = await fetch(`/api${path}`, { method, headers, credentials: 'same-origin', body: body === undefined ? undefined : JSON.stringify(body), }) if (!response.ok) { if (response.status === 401 && path !== '/auth/login') onUnauthorized?.() throw new ApiError(response.status, await errorMessage(response)) } if (response.status === 204) return undefined as T return (await response.json()) as T } export const api = { get: (path: string) => apiRequest('GET', path), post: (path: string, body?: unknown) => apiRequest('POST', path, body), patch: (path: string, body?: unknown) => apiRequest('PATCH', path, body), delete: (path: string) => apiRequest('DELETE', path), }