import { reactive } from 'vue'; export class ApiError extends Error { constructor(public status: number, public body: any) { super(body?.message ?? `HTTP ${status}`); } /** Validation errors by field, first message each. */ get errors(): Record { return Object.fromEntries(Object.entries(this.body?.errors ?? {}).map(([k, v]) => [k, (v as string[])[0]])); } } export interface NavItem { label: string; href: string; section?: string; icon?: string; new_tab?: boolean; } /** What the page was started with (see resources/views/shell.blade.php). */ export interface Boot { base: string; name: string; logo: string | null; locale: string; user: { name: string; email: string; is_super_admin: boolean } | null; permissions: string[]; navigation: NavItem[]; view: 'full' | 'simple'; extensions: string[]; can_switch: boolean; theme: string; can_login: boolean; } export const boot: Boot = JSON.parse(document.getElementById('manager-boot')!.textContent!); function xsrf(): string { const match = document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]+)/); return match ? decodeURIComponent(match[1]) : ''; } export async function request(method: string, path: string, body?: unknown): Promise { const response = await fetch(path, { method, credentials: 'same-origin', headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-XSRF-TOKEN': xsrf(), ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), }, body: body === undefined ? undefined : JSON.stringify(body), }); const data = response.status === 204 ? null : await response.json().catch(() => null); if (!response.ok) { throw new ApiError(response.status, data); } return data as T; } /** A file upload: multipart, the browser sets the content type. */ export async function upload(path: string, form: FormData): Promise { const response = await fetch(path, { method: 'POST', credentials: 'same-origin', headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-XSRF-TOKEN': xsrf() }, body: form, }); const data = await response.json().catch(() => null); if (!response.ok) { throw new ApiError(response.status, data); } return data as T; } export const api = { get: (path: string) => request('GET', path), post: (path: string, body: unknown = {}) => request('POST', path, body), put: (path: string, body: unknown = {}) => request('PUT', path, body), delete: (path: string, body?: unknown) => request('DELETE', path, body), }; /** A form: values, errors by field, a busy flag. */ export function useForm>(initial: T) { const form = reactive({ values: { ...initial } as T, errors: {} as Record, busy: false, async send(method: 'post' | 'put', path: string): Promise { form.busy = true; form.errors = {}; try { return await api[method](path, form.values); } catch (error) { if (error instanceof ApiError && error.status === 422) { form.errors = error.errors; return null; } throw error; } finally { form.busy = false; } }, }); return form; }