// API Client for CLQMS // Wrapper around fetch for making API calls to the backend import { browser } from '$app/environment'; import { PUBLIC_API_BASE_URL, PUBLIC_API_BASE_URL_PROD } from '$env/static/public'; const API_BASE_URL = browser ? (import.meta.env.DEV ? PUBLIC_API_BASE_URL : PUBLIC_API_BASE_URL_PROD) : PUBLIC_API_BASE_URL; interface ApiError { message: string; status: number; code?: string; } interface ApiResponse { data: T | null; error: ApiError | null; success: boolean; } class ApiClient { private baseUrl: string; private defaultHeaders: Record; constructor(baseUrl: string = API_BASE_URL) { this.baseUrl = baseUrl.replace(/\/$/, ''); this.defaultHeaders = { 'Content-Type': 'application/json', 'Accept': 'application/json' }; } private async request( endpoint: string, options: RequestInit = {} ): Promise> { const url = `${this.baseUrl}/${endpoint.replace(/^\//, '')}`; const config: RequestInit = { ...options, headers: { ...this.defaultHeaders, ...options.headers }, credentials: 'include' }; try { const response = await fetch(url, config); if (!response.ok) { const errorData = await response.json().catch(() => ({})); return { data: null, error: { message: errorData.message || `HTTP Error: ${response.status}`, status: response.status, code: errorData.code }, success: false }; } const contentType = response.headers.get('content-type'); let data: T; if (contentType?.includes('application/json')) { data = await response.json(); } else { data = await response.text() as unknown as T; } return { data, error: null, success: true }; } catch (error) { return { data: null, error: { message: error instanceof Error ? error.message : 'Network error', status: 0 }, success: false }; } } async get(endpoint: string, headers?: Record): Promise> { return this.request(endpoint, { method: 'GET', headers }); } async post( endpoint: string, body: unknown, headers?: Record ): Promise> { return this.request(endpoint, { method: 'POST', body: JSON.stringify(body), headers }); } async patch( endpoint: string, body: unknown, headers?: Record ): Promise> { return this.request(endpoint, { method: 'PATCH', body: JSON.stringify(body), headers }); } async put( endpoint: string, body: unknown, headers?: Record ): Promise> { return this.request(endpoint, { method: 'PUT', body: JSON.stringify(body), headers }); } async delete(endpoint: string, headers?: Record): Promise> { return this.request(endpoint, { method: 'DELETE', headers }); } } export const api = new ApiClient(); export type { ApiResponse, ApiError };