/** * Base API Client for HTTP operations * * Provides generic HTTP methods with common request/response handling, * error handling, and authentication. */ export class BaseApiClient { private baseUrl: string; constructor(baseUrl: string) { this.baseUrl = baseUrl; } protected async request(method: string, path: string, data?: object): Promise { const headers: HeadersInit = { 'Content-Type': 'application/json', }; const config: RequestInit = { method, headers, credentials: 'include', // Include cookies for auth }; if (data) { config.body = JSON.stringify(data); } const response = await fetch(`${this.baseUrl}${path}`, config); if (!response.ok) { let errorData: { message?: string } = { message: response.statusText }; try { errorData = await response.json(); } catch { // Keep default error message } throw new Error(errorData.message || `API request failed with status ${response.status}`); } const text = await response.text(); if (!text) { return null as T; } return JSON.parse(text) as T; } protected get(path: string): Promise { return this.request('GET', path); } protected post(path: string, data: object): Promise { return this.request('POST', path, data); } protected put(path: string, data: object): Promise { return this.request('PUT', path, data); } protected delete(path: string): Promise { return this.request('DELETE', path); } protected patch(path: string, data: object): Promise { return this.request('PATCH', path, data); } }