import { TOKEN } from "@/constants"; import { getStorageItem } from "@/utils/storage"; import axios, { AxiosInstance } from "axios"; import { showToastError } from "./toast"; const codeMessage = { 200: "The server successfully returned the requested data。", 201: "New or modified data succeeded。", 202: "A request has been queued in the background (asynchronous task)。", 204: "Data deleted successfully。", 400: "There is an error in the request sent, the server did not perform the operation of creating or modifying data。", 401: "The user does not have permission (token, username, password is wrong) 。", 403: "User is authorized, but access is prohibited。", 404: "The request issued was for a non-existent record, the server did not operate。", 406: "The requested format is not available。", 410: "The requested resource is permanently deleted and will no longer be available。", 422: "When creating an object, a validation error occurred。", 500: "Server error, please check the server。", 502: "Gateway error。", 503: "Service unavailable, server temporarily overloaded or maintained。", 504: "Gateway timeout。", }; // Tạo instance axios với cấu hình cơ bản const api: AxiosInstance = axios.create({ baseURL: "http://192.168.30.102:81", // Thay bằng API thật của bạn timeout: 10000, // Timeout 10 giây headers: { "Content-Type": "application/json", }, }); console.log("🚀 Axios baseURL:", api.defaults.baseURL); // Interceptor cho request (thêm token nếu cần) api.interceptors.request.use( async (config) => { // Thêm auth token nếu có const token = await getStorageItem(TOKEN); if (token) { config.headers.Authorization = `${token}`; } return config; }, (error) => { return Promise.reject(error); } ); // Interceptor cho response (xử lý lỗi chung) api.interceptors.response.use( (response) => { return response; }, (error) => { if (!error.response) { const networkErrorMsg = error.message || "Network error - please check connection"; showToastError("Lỗi kết nối", networkErrorMsg); return Promise.reject(error); } const { status, statusText, data } = error.response; // Ưu tiên: codeMessage → backend message → statusText const errMsg = codeMessage[status as keyof typeof codeMessage] || data?.message || statusText || "Unknown error"; showToastError(`Lỗi ${status}`, errMsg); if (status === 401) { // handle401(); } return Promise.reject(error); } ); export default api;