import { ApiConfig, ApiResponse } from '../types/types'; export class IdentityClient { private static instance: IdentityClient | null = null; private config: ApiConfig; private headers: Record; // Private constructor prevents direct instantiation private constructor(config: ApiConfig) { this.config = config; this.headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${this.config.apiKey}`, }; } // Static method to get the singleton instance public static getInstance(config?: ApiConfig): IdentityClient { if (!IdentityClient.instance) { if (!config) { throw new Error( 'IdentityClient configuration is required for first initialization' ); } IdentityClient.instance = new IdentityClient(config); } return IdentityClient.instance; } // Method to update configuration (optional) public updateConfig(config: Partial): void { this.config = { ...this.config, ...config }; } // Method to get current configuration public getConfig(): ApiConfig { return { ...this.config }; } // Method to reset singleton (useful for testing) public static reset(): void { IdentityClient.instance = null; } private async makeRequest( endpoint: string, options: RequestInit = {} ): Promise> { try { const controller = new AbortController(); const timeoutId = this.config.timeout ? setTimeout(() => controller.abort(), this.config.timeout) : null; const response = await fetch(`${this.config.baseUrl}${endpoint}`, { headers: this.headers, credentials: 'include', signal: controller.signal, ...options, }); if (timeoutId) { clearTimeout(timeoutId); } const data = await response.json(); return { data, success: response.ok, message: response.ok ? 'Success' : data.message || 'Request failed', }; } catch (error) { const isAbortError = error instanceof Error && error.name === 'AbortError'; const errorMessage = isAbortError ? 'Request timeout' : error instanceof Error ? error.message : 'Unknown error'; return { data: null as any, success: false, message: errorMessage, }; } } async get(endpoint: string): Promise> { return this.makeRequest(endpoint, { method: 'GET' }); } async post(endpoint: string, body: any): Promise> { return this.makeRequest(endpoint, { method: 'POST', body: JSON.stringify(body), }); } async put(endpoint: string, body: any): Promise> { return this.makeRequest(endpoint, { method: 'PUT', body: JSON.stringify(body), }); } async delete(endpoint: string): Promise> { return this.makeRequest(endpoint, { method: 'DELETE' }); } } // Export a factory function for easier usage export const createIdentityClient = (config: ApiConfig): IdentityClient => { return IdentityClient.getInstance(config); }; // Export a function to get existing instance export const getIdentityClient = (): IdentityClient => { return IdentityClient.getInstance(); };