diff --git a/src/components/Global/ApiRequest.jsx b/src/components/Global/ApiRequest.jsx index ad37baa..52947a2 100644 --- a/src/components/Global/ApiRequest.jsx +++ b/src/components/Global/ApiRequest.jsx @@ -5,9 +5,16 @@ const baseURL = import.meta.env.VITE_API_SERVER; const instance = axios.create({ baseURL, - withCredentials: true, + withCredentials: true, }); +// axios khusus refresh +const refreshApi = axios.create({ + baseURL, + withCredentials: true, +}); + + instance.interceptors.response.use( (response) => response, async (error) => { @@ -17,15 +24,13 @@ instance.interceptors.response.use( originalRequest._retry = true; try { - const refreshRes = await axios.post( - `${baseURL}/auth/refresh`, - {}, - { withCredentials: true } - ); + console.log("🔄 Refresh token dipanggil..."); + const refreshRes = await refreshApi.post("/auth/refresh-token"); - const newAccessToken = refreshRes.data.accessToken; + const newAccessToken = refreshRes.data.data.accessToken; localStorage.setItem("token", newAccessToken); + // update token di header instance.defaults.headers.common["Authorization"] = `Bearer ${newAccessToken}`; originalRequest.headers["Authorization"] = `Bearer ${newAccessToken}`; @@ -57,11 +62,9 @@ async function ApiRequest({ "Accept-Language": "en_US", ...(isFormData ? {} : { "Content-Type": "application/json" }), }, - withCredentials: true, }; const rawToken = localStorage.getItem("token"); - if (token && rawToken) { request.headers["Authorization"] = `Bearer ${rawToken.replace(/"/g, "")}`; } @@ -73,23 +76,27 @@ async function ApiRequest({ const status = error?.response?.status || 500; const message = error?.response?.data?.message || error.message || "Something Wrong"; - await cekError(status, message); + if (status !== 401) { + await cekError(status, message); + } + return { ...error.response, error: true }; } } -// =============================== -// Global error handler -// =============================== async function cekError(status, message = "") { - if (status === 401) { + if (status === 403) { await Swal.fire({ icon: "warning", - title: "Peringatan", - text: `${message}, Silahkan login`, + title: "Forbidden", + text: message, + }); + } else if (status >= 500) { + await Swal.fire({ + icon: "error", + title: "Server Error", + text: message, }); - localStorage.clear(); - window.location.href = "/signin"; } else { await Swal.fire({ icon: "warning", @@ -99,16 +106,16 @@ async function cekError(status, message = "") { } } -// =============================== -// Wrapper simpler -// =============================== const SendRequest = async (queryParams) => { try { const response = await ApiRequest(queryParams); return response?.data || []; } catch (error) { console.error("Request error:", error); - await Swal.fire({ icon: "error", text: error.message || "Something went wrong" }); + await Swal.fire({ + icon: "error", + text: error.message || "Something went wrong", + }); return []; } };