Spaces:
Runtime error

vibra / fe /src /api /client.ts
valent-p's picture
chore: update node_modules dependencies and project configuration files
330c3b5
Raw History Blame Contribute Delete
1.93 kB
const BASE_URL = import.meta.env.DEV ? 'http://localhost:8000' : '';
interface RequestOptions extends RequestInit {
params?: Record<string, string>;
}
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
const token = localStorage.getItem('vibra_token');
// Setup headers
const headers = new Headers(options.headers);
if (token && !headers.has('Authorization')) {
headers.set('Authorization', `Bearer ${token}`);
}
if (!headers.has('Content-Type') && !(options.body instanceof FormData)) {
headers.set('Content-Type', 'application/json');
}
// Setup Query parameters
let url = `${BASE_URL}${path}`;
if (options.params) {
const searchParams = new URLSearchParams(options.params);
url += `?${searchParams.toString()}`;
}
const response = await fetch(url, {
...options,
headers,
});
if (!response.ok) {
let errorMessage = `Request failed: ${response.statusText}`;
try {
const errorData = await response.json();
errorMessage = errorData.detail || errorMessage;
} catch {
// JSON parsing failed, use fallback message
}
throw new Error(errorMessage);
}
// Return empty response if 204 No Content
if (response.status === 204) {
return {} as T;
}
return response.json();
}
export const api = {
get: <T>(path: string, options?: RequestOptions) =>
request<T>(path, { ...options, method: 'GET' }),
post: <T>(path: string, body?: any, options?: RequestOptions) =>
request<T>(path, {
...options,
method: 'POST',
body: body instanceof FormData ? body : JSON.stringify(body)
}),
put: <T>(path: string, body?: any, options?: RequestOptions) =>
request<T>(path, {
...options,
method: 'PUT',
body: JSON.stringify(body)
}),
delete: <T>(path: string, options?: RequestOptions) =>
request<T>(path, { ...options, method: 'DELETE' }),
};