Files
pos/resources/js/admin/tailadmin/lib/api.ts
2026-03-06 03:26:11 +07:00

118 lines
2.8 KiB
TypeScript

type Json = Record<string, any>;
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<T = any>(path: string): Promise<T> {
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<T = any>(path: string, body: Json): Promise<T> {
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<T = any>(path: string, body: Json): Promise<T> {
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<T = any>(path: string): Promise<T> {
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<string> {
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})`;
}