%PDF- %PDF-
| Direktori : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/lib/ |
| Current File : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/lib/api.ts |
import { ApiError, type ApiErrorBody } from "@/types/api";
/**
* Base URL backend.
* - Kosong (default) → pakai proxy Vite (konfigurasi vite.config.ts).
* - Bisa di-override via VITE_API_BASE_URL (lihat .env.example).
*/
const BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? "";
interface RequestOptions {
method?: string;
body?: unknown;
signal?: AbortSignal;
}
export async function apiRequest<T>(
path: string,
options: RequestOptions = {},
): Promise<T> {
const { method = "GET", body, signal } = options;
const headers: Record<string, string> = {};
if (body !== undefined) headers["Content-Type"] = "application/json";
// Semua panggilan internal lewat /api (prefix backend) — 1 choke point,
// sehingga 40+ call site di aplikasi tidak perlu diubah satu per satu.
const url = path.startsWith("/api") ? path : `/api${path}`;
const res = await fetch(`${BASE_URL}${url}`, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
signal,
credentials: "include",
});
// 204 / respons kosong
if (res.status === 204) return undefined as T;
const data = (await res.json().catch(() => null)) as ApiErrorBody | T | null;
if (!res.ok) {
const msg =
(data as ApiErrorBody)?.error?.message ??
`Permintaan gagal (HTTP ${res.status})`;
const type = (data as ApiErrorBody)?.error?.type;
throw new ApiError(msg, res.status, type);
}
return data as T;
}