mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-27 21:20:57 +00:00
71 lines
2.3 KiB
TypeScript
71 lines
2.3 KiB
TypeScript
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
|
|
|
|
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000';
|
|
|
|
class ApiClient {
|
|
private client: AxiosInstance;
|
|
|
|
constructor() {
|
|
this.client = axios.create({
|
|
baseURL: API_URL,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
|
|
this.client.interceptors.request.use((config) => {
|
|
const token = typeof window !== 'undefined' ? localStorage.getItem('auth_token') : null;
|
|
if (token && token !== 'null' && token !== 'undefined') {
|
|
config.headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
return config;
|
|
});
|
|
|
|
const PUBLIC_PREFIXES = ['/config/', '/auth/login', '/auth/register', '/passengers/me'];
|
|
|
|
this.client.interceptors.response.use(
|
|
(response) => response,
|
|
(error) => {
|
|
if (error.response?.status === 401) {
|
|
const url: string = error.config?.url || '';
|
|
const isPublic = PUBLIC_PREFIXES.some((p) => url.includes(p));
|
|
if (!isPublic && typeof window !== 'undefined') {
|
|
localStorage.removeItem('auth_token');
|
|
localStorage.removeItem('auth_user');
|
|
window.location.href = '/login';
|
|
}
|
|
}
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
}
|
|
|
|
async get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
|
|
const response = await this.client.get<any>(url, config);
|
|
// Handle both direct data and wrapped responses
|
|
return response.data?.data || response.data;
|
|
}
|
|
|
|
async post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
|
|
const response = await this.client.post<any>(url, data, config);
|
|
return response.data?.data || response.data;
|
|
}
|
|
|
|
async put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
|
|
const response = await this.client.put<T>(url, data, config);
|
|
return response.data;
|
|
}
|
|
|
|
async patch<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
|
|
const response = await this.client.patch<T>(url, data, config);
|
|
return response.data;
|
|
}
|
|
|
|
async delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
|
|
const response = await this.client.delete<T>(url, config);
|
|
return response.data;
|
|
}
|
|
}
|
|
|
|
export const apiClient = new ApiClient();
|