Files
OnEverControl/frontend/src/api/client.ts
T

52 lines
1.5 KiB
TypeScript

// ==============================================================================
// Cliente HTTP Fetch con soporte para cookies HttpOnly y tipado estricto
// ==============================================================================
const BASE_URL = '/api/v1';
export class ApiError extends Error {
status: number;
data: any;
constructor(status: number, message: string, data?: any) {
super(message);
this.status = status;
this.data = data;
this.name = 'ApiError';
}
}
export async function request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
const url = endpoint.startsWith('http') ? endpoint : `${BASE_URL}${endpoint}`;
const headers = new Headers(options.headers || {});
if (!headers.has('Content-Type') && !(options.body instanceof FormData)) {
headers.set('Content-Type', 'application/json');
}
const response = await fetch(url, {
...options,
headers,
credentials: 'include', // Para incluir cookie HttpOnly access_token
});
if (response.status === 204) {
return {} as T;
}
const contentType = response.headers.get('content-type');
let data: any = null;
if (contentType && contentType.includes('application/json')) {
data = await response.json();
} else {
data = await response.text();
}
if (!response.ok) {
const errorMsg = data?.detail || data?.message || `Error HTTP ${response.status}`;
throw new ApiError(response.status, errorMsg, data);
}
return data as T;
}