Files
towercontrol/clients/base/http-client.ts
2025-09-17 08:30:36 +02:00

80 lines
2.0 KiB
TypeScript

/**
* Client HTTP de base pour toutes les requêtes API
*/
export class HttpClient {
private baseUrl: string;
constructor(baseUrl: string = '') {
this.baseUrl = baseUrl;
}
private async request<T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
const url = `${this.baseUrl}${endpoint}`;
const config: RequestInit = {
headers: {
'Content-Type': 'application/json',
...options.headers,
},
...options,
};
try {
const response = await fetch(url, config);
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error(`HTTP Request failed: ${url}`, error);
throw error;
}
}
async get<T>(endpoint: string, params?: Record<string, string>): Promise<T> {
const url = params
? `${endpoint}?${new URLSearchParams(params)}`
: endpoint;
return this.request<T>(url, { method: 'GET' });
}
async post<T>(endpoint: string, data?: unknown): Promise<T> {
return this.request<T>(endpoint, {
method: 'POST',
body: data ? JSON.stringify(data) : undefined,
});
}
async put<T>(endpoint: string, data?: unknown): Promise<T> {
return this.request<T>(endpoint, {
method: 'PUT',
body: data ? JSON.stringify(data) : undefined,
});
}
async patch<T>(endpoint: string, data?: unknown): Promise<T> {
return this.request<T>(endpoint, {
method: 'PATCH',
body: data ? JSON.stringify(data) : undefined,
});
}
async delete<T>(endpoint: string, params?: Record<string, string>): Promise<T> {
const url = params
? `${endpoint}?${new URLSearchParams(params)}`
: endpoint;
return this.request<T>(url, { method: 'DELETE' });
}
}
// Instance par défaut
export const httpClient = new HttpClient('/api');