glam/packages/api-client/src/clients/base.ts
2025-12-21 00:01:54 +01:00

61 lines
1.8 KiB
TypeScript

/**
* @glam/api-client - Base API client
*/
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
import { getApiConfig, ApiConfig } from '../config';
export class BaseApiClient {
protected client: AxiosInstance;
protected config: ApiConfig;
constructor(baseURL: string, options: AxiosRequestConfig = {}) {
this.config = getApiConfig();
this.client = axios.create({
baseURL,
timeout: 30000,
headers: {
'Content-Type': 'application/json',
},
...options,
});
// Request interceptor for logging
this.client.interceptors.request.use(
(config) => {
console.debug(`[API] ${config.method?.toUpperCase()} ${config.url}`);
return config;
},
(error) => Promise.reject(error)
);
// Response interceptor for error handling
this.client.interceptors.response.use(
(response) => response,
(error) => {
console.error('[API Error]', error.response?.data || error.message);
return Promise.reject(error);
}
);
}
protected async get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
const response = await this.client.get<T>(url, config);
return response.data;
}
protected async post<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {
const response = await this.client.post<T>(url, data, config);
return response.data;
}
protected async put<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {
const response = await this.client.put<T>(url, data, config);
return response.data;
}
protected async delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
const response = await this.client.delete<T>(url, config);
return response.data;
}
}