gMAS / web_ui /frontend /src /lib /api.ts
Артём Боярских
chore: initial commit
3193174
const BASE_URL = "/api";
async function request<T>(
method: string,
endpoint: string,
data?: unknown,
): Promise<T> {
const options: RequestInit = {
method,
headers: { "Content-Type": "application/json" },
};
if (data !== undefined) {
options.body = JSON.stringify(data);
}
const response = await fetch(`${BASE_URL}${endpoint}`, options);
if (!response.ok) {
const text = await response.text().catch(() => response.statusText);
throw new Error(text || `${method} ${endpoint} failed (${response.status})`);
}
if (response.status === 204) {
return undefined as T;
}
return response.json() as Promise<T>;
}
export const api = {
get: <T>(endpoint: string) => request<T>("GET", endpoint),
post: <T>(endpoint: string, data?: unknown) => request<T>("POST", endpoint, data),
put: <T>(endpoint: string, data?: unknown) => request<T>("PUT", endpoint, data),
delete: (endpoint: string) => request<void>("DELETE", endpoint),
};