117 lines
3.6 KiB
TypeScript
117 lines
3.6 KiB
TypeScript
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<string, string> {
|
|
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<T = any>(method: string, path: string, body?: unknown): Promise<T> {
|
|
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<T = any>(path: string, form: FormData): Promise<T> {
|
|
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: <T = any>(path: string) => request<T>('GET', path),
|
|
post: <T = any>(path: string, body: unknown = {}) => request<T>('POST', path, body),
|
|
put: <T = any>(path: string, body: unknown = {}) => request<T>('PUT', path, body),
|
|
delete: <T = any>(path: string, body?: unknown) => request<T>('DELETE', path, body),
|
|
};
|
|
|
|
/** A form: values, errors by field, a busy flag. */
|
|
export function useForm<T extends Record<string, any>>(initial: T) {
|
|
const form = reactive({
|
|
values: { ...initial } as T,
|
|
errors: {} as Record<string, string>,
|
|
busy: false,
|
|
async send<R = any>(method: 'post' | 'put', path: string): Promise<R | null> {
|
|
form.busy = true;
|
|
form.errors = {};
|
|
try {
|
|
return await api[method]<R>(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;
|
|
}
|