UNPKG

@tech-arelius/api-client

Version:

Configurable HTTP client with builder pattern for Node.js/TypeScript

91 lines (76 loc) 2.89 kB
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; import { Interceptor } from '../interceptor/Interceptor'; /** * Main API client with prebuilt methods and convenience functions */ export class ApiClient { private axiosInstance: AxiosInstance; private defaultHeaders: Record<string, string> = {}; constructor( baseUrl?: string, timeout?: number, defaultHeaders?: Record<string, string>, interceptors?: Interceptor[] ) { this.defaultHeaders = defaultHeaders || {}; this.axiosInstance = axios.create({ baseURL: baseUrl, timeout: timeout, headers: { ...this.defaultHeaders } }); // Add interceptors if (interceptors) { interceptors.forEach(interceptor => { if (interceptor.onRequest) { this.axiosInstance.interceptors.request.use(interceptor.onRequest); } if (interceptor.onResponse) { this.axiosInstance.interceptors.response.use(interceptor.onResponse); } if (interceptor.onError) { this.axiosInstance.interceptors.response.use( response => response, interceptor.onError ); } }); } } /** * Core HTTP methods - direct axios pass-throughs */ async get(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse> { const response = await this.axiosInstance.get(url, config); return response; } async post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse> { const response = await this.axiosInstance.post<T>(url, data, config); return response; } async put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse> { const response = await this.axiosInstance.put<T>(url, data, config); return response; } async delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse> { const response = await this.axiosInstance.delete<T>(url, config); return response; } async patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse> { const response = await this.axiosInstance.patch<T>(url, data, config); return response; } async head<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse> { const response = await this.axiosInstance.head<T>(url, config); return response; } async options<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse> { const response = await this.axiosInstance.options<T>(url, config); return response; } async request<T = any>(config: AxiosRequestConfig): Promise<AxiosResponse> { const response = await this.axiosInstance.request<T>(config); return response; } }