/** * JSON-Anfragen an das Portal (außerhalb von Inertia-Seitenwechseln), mit * CSRF-Schutz über das XSRF-TOKEN-Cookie von Laravel. */ function xsrfToken() { const match = document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]*)/); return match ? decodeURIComponent(match[1]) : ''; } export class HttpError extends Error { constructor(status, data) { super(data?.message || `Anfrage fehlgeschlagen (${status})`); this.status = status; this.data = data ?? {}; } /** Erste Fehlermeldung je Feld aus einer 422-Antwort. */ get fieldErrors() { return Object.fromEntries(Object.entries(this.data.errors ?? {}).map(([key, messages]) => [key, messages[0]])); } } export async function request(method, url, body, options = {}) { const headers = { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-XSRF-TOKEN': xsrfToken(), }; let payload = body; if (body !== undefined && !(body instanceof FormData)) { headers['Content-Type'] = 'application/json'; payload = JSON.stringify(body); } const response = await fetch(url, { method, headers, body: payload, credentials: 'same-origin', keepalive: options.keepalive ?? false }); const data = response.headers.get('content-type')?.includes('application/json') ? await response.json() : null; if (!response.ok) { throw new HttpError(response.status, data); } return data; } export const http = { get: (url) => request('GET', url), post: (url, body, options) => request('POST', url, body ?? {}, options), put: (url, body) => request('PUT', url, body), delete: (url, body) => request('DELETE', url, body), };