import axios from "axios"; import type { AxiosError } from "axios"; import type { AxiosRequestConfig, AxiosResponse } from "axios"; import { runtimeConfig } from "@/Utils/runtimeConfig"; const BASE_URL = runtimeConfig.apiBaseUrl || import.meta.env.VITE_APP_API_BASE_URL || "/api/v1"; const api = axios.create({ baseURL: BASE_URL, }); type StoreType = { getState: () => { auth?: { authToken?: string } }; }; let storeInstance: StoreType | null = null; let interceptorsInitialized = false; type ServerUnreachableCallback = (unreachable: boolean) => void; let serverUnreachableCallback: ServerUnreachableCallback | null = null; export const setServerUnreachableCallback = ( callback: ServerUnreachableCallback ): void => { serverUnreachableCallback = callback; }; export const initApiClient = (store: StoreType): void => { storeInstance = store; if (interceptorsInitialized) { return; } interceptorsInitialized = true; api.interceptors.request.use( (config) => { const authToken = storeInstance?.getState()?.auth?.authToken ?? ""; config.headers.set("Authorization", `Bearer ${authToken}`); if (!config.headers.has("Accept-Language")) { config.headers.set("Accept-Language", "en"); } return config; }, (error) => { return Promise.reject(error); } ); const onSuccess = (response: AxiosResponse) => { // Server is reachable, hide offline banner if shown serverUnreachableCallback?.(false); return response; }; const onError = (error: AxiosError) => { // Handle network errors (server unreachable) if (error.code === "ERR_NETWORK") { serverUnreachableCallback?.(true); return Promise.reject(error); } if (error.response?.status === 401) { if (window.location.pathname !== "/login") { window.location.href = "/login"; } } return Promise.reject(error); }; api.interceptors.response.use(onSuccess, onError); }; export const get = ( url: string, config: AxiosRequestConfig = {} ): Promise> => api.get(url, config); export const post = ( url: string, data: unknown, config: AxiosRequestConfig = {} ): Promise> => api.post(url, data, config); export const patch = ( url: string, data: unknown, config: AxiosRequestConfig = {} ): Promise> => api.patch(url, data, config); export const put = ( url: string, data: unknown, config: AxiosRequestConfig = {} ): Promise> => api.put(url, data, config); export const deleteOp = ( url: string, config: AxiosRequestConfig = {} ): Promise> => api.delete(url, config); export default api;