| |
| import axios, { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse, AxiosError } from "axios"; |
| import { toast } from "sonner"; |
|
|
| |
| const API_URL: string = |
| import.meta.env.VITE_API_URL || "https://dev.api.naturalproducts.net/latest"; |
|
|
| |
| const api: AxiosInstance = axios.create({ |
| baseURL: API_URL, |
| headers: { |
| "Content-Type": "application/json", |
| }, |
| timeout: 30000, |
| }); |
|
|
| |
| api.interceptors.request.use( |
| (config: InternalAxiosRequestConfig) => { |
| |
| return config; |
| }, |
| (error: unknown) => { |
| return Promise.reject(error); |
| } |
| ); |
|
|
| |
| api.interceptors.response.use( |
| (response: AxiosResponse) => { |
| return response; |
| }, |
| (error: unknown) => { |
| const axiosError = error as AxiosError; |
| if (import.meta.env.DEV) { |
| if (axiosError.response) { |
| console.error("API Error Response:", axiosError.response.status); |
| } else if (axiosError.request) { |
| console.error("API No Response"); |
| } else if (error instanceof Error) { |
| console.error("API Request Error:", error.message); |
| } |
| } |
|
|
| const status = axiosError.response?.status; |
|
|
| |
| if (!axiosError.response || (status && status >= 500)) { |
| toast.error("Service temporarily unavailable", { |
| id: "network-error", |
| description: "Please try again in a moment.", |
| duration: 5000, |
| }); |
| } |
|
|
| |
| if (status === 429) { |
| toast.error("Too many requests", { |
| id: "rate-limit", |
| description: "Please wait before trying again.", |
| duration: 5000, |
| }); |
| } |
|
|
| |
| return Promise.reject(error); |
| } |
| ); |
|
|
| export default api; |
|
|