UNPKG

@wizecorp/stratusjs

Version:
58 lines (48 loc) 1.45 kB
/** * HTTP Service for API calls * Provides a centralized way to make HTTP requests with proper error handling */ export class HttpService { private baseUrl: string; constructor(baseUrl: string = 'https://jsonplaceholder.typicode.com') { 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) { throw new Error(`HTTP Error: ${response.status} ${response.statusText}`); } return await response.json(); } catch (error) { console.error('API Request failed:', error); throw error; } } async get<T>(endpoint: string): Promise<T> { return this.request<T>(endpoint, { method: 'GET' }); } async post<T>(endpoint: string, data: any): Promise<T> { return this.request<T>(endpoint, { method: 'POST', body: JSON.stringify(data), }); } async put<T>(endpoint: string, data: any): Promise<T> { return this.request<T>(endpoint, { method: 'PUT', body: JSON.stringify(data), }); } async delete<T>(endpoint: string): Promise<T> { return this.request<T>(endpoint, { method: 'DELETE' }); } }