type Json = Record; function getBase(): string { return ( document.querySelector('meta[name="app-base"]')?.getAttribute("content") || "" ); } function getCsrf(): string { return ( document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "" ); } export async function apiGet(path: string): Promise { const base = getBase(); const res = await fetch(`${base}${path}`, { method: "GET", credentials: "same-origin", headers: { Accept: "application/json", }, }); if (!res.ok) { const message = await readErrorMessage(res); throw new Error(message); } return (await res.json()) as T; } export async function apiPost(path: string, body: Json): Promise { const base = getBase(); const csrf = getCsrf(); const res = await fetch(`${base}${path}`, { method: "POST", credentials: "same-origin", headers: { Accept: "application/json", "Content-Type": "application/json", "X-CSRF-TOKEN": csrf, }, body: JSON.stringify(body), }); if (!res.ok) { const message = await readErrorMessage(res); throw new Error(message); } return (await res.json()) as T; } export async function apiPut(path: string, body: Json): Promise { const base = getBase(); const csrf = getCsrf(); const res = await fetch(`${base}${path}`, { method: "PUT", credentials: "same-origin", headers: { Accept: "application/json", "Content-Type": "application/json", "X-CSRF-TOKEN": csrf, }, body: JSON.stringify(body), }); if (!res.ok) { const message = await readErrorMessage(res); throw new Error(message); } return (await res.json()) as T; } export async function apiDelete(path: string): Promise { const base = getBase(); const csrf = getCsrf(); const res = await fetch(`${base}${path}`, { method: "DELETE", credentials: "same-origin", headers: { Accept: "application/json", "X-CSRF-TOKEN": csrf, }, }); if (!res.ok) { const message = await readErrorMessage(res); throw new Error(message); } return (await res.json()) as T; } async function readErrorMessage(res: Response): Promise { let text = ""; try { text = await res.text(); } catch {} let message = text || ""; const looksLikeJson = message.trim().startsWith("{") || message.trim().startsWith("["); if (looksLikeJson) { try { const json = JSON.parse(message); if (json?.message) message = json.message; else if (json?.error) message = json.error; else if (json?.errors) { message = Object.values(json.errors).flat().join(" "); } } catch {} } message = message.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim(); return message || `Permintaan gagal (${res.status})`; }