ff-admin/src/serverCom.ts

78 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-08-22 09:48:04 +00:00
import axios from "axios";
2024-08-25 11:37:23 +00:00
let devMode = process.env.NODE_ENV === "development";
2024-08-22 09:48:04 +00:00
const http = axios.create({
2024-08-25 11:37:23 +00:00
baseURL: devMode ? "http://localhost:5000" : server_adress,
2024-08-22 09:48:04 +00:00
headers: {
"Cache-Control": "no-cache",
Pragma: "no-cache",
Expires: "0",
},
});
http.interceptors.request.use(
(config) => {
const token = localStorage.getItem("accessToken");
if (token) {
if (config.headers) {
config.headers.Authorization = `Bearer ${token}`;
}
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
http.interceptors.response.use(
(response) => {
return response;
},
async (error) => {
2024-08-25 11:37:23 +00:00
if (!error.config.url.includes("/admin")) {
2024-08-23 12:42:32 +00:00
return Promise.reject(error);
}
2024-08-22 09:48:04 +00:00
const originalRequest = error.config;
// Handle token expiration and retry the request with a refreshed token
if (error.response && error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
return await refreshToken()
.then(() => {
return http(originalRequest);
})
.catch();
}
return Promise.reject(error);
}
);
2024-08-25 08:10:11 +00:00
export async function refreshToken(): Promise<void> {
2024-08-22 09:48:04 +00:00
return new Promise<void>(async (resolve, reject) => {
await http
.post(`/auth/refresh`, {
2024-08-25 08:10:11 +00:00
accessToken: localStorage.getItem("accessToken"),
2024-08-22 09:48:04 +00:00
refreshToken: localStorage.getItem("refreshToken"),
})
.then((response) => {
2024-08-25 08:10:11 +00:00
const { accessToken, refreshToken } = response.data;
2024-08-22 09:48:04 +00:00
2024-08-25 08:10:11 +00:00
localStorage.setItem("accessToken", accessToken);
2024-08-22 09:48:04 +00:00
localStorage.setItem("refreshToken", refreshToken);
resolve();
})
.catch((error) => {
console.error("Error refreshing token:", error);
reject();
});
});
}
export { http };