ff-admin-webapi-client/src/http.ts

66 lines
1.6 KiB
TypeScript
Raw Normal View History

2025-01-28 15:39:30 +01:00
import axios, { AxiosInstance } from "axios";
2025-02-05 14:29:09 +01:00
import { BaseClient } from "./clients/clientBase";
2025-01-28 15:39:30 +01:00
2025-02-05 14:29:09 +01:00
export default class HTTP {
2025-01-28 15:39:30 +01:00
public http: AxiosInstance;
2025-02-05 14:29:09 +01:00
private client: BaseClient;
2025-01-28 15:39:30 +01:00
2025-02-05 14:29:09 +01:00
constructor(client: BaseClient) {
this.client = client;
2025-01-28 15:39:30 +01:00
this.http = axios.create({
2025-02-05 14:29:09 +01:00
baseURL: this.client.serverAdress + "/api",
2025-01-28 15:39:30 +01:00
headers: {
"Cache-Control": "no-cache",
Pragma: "no-cache",
Expires: "0",
},
});
this.setRequestInterceptor();
this.setResponseInterceptor();
}
private setRequestInterceptor() {
this.http.interceptors.request.use(
(config) => {
if (config.headers && config.headers.Authorization == "") {
2025-02-05 14:29:09 +01:00
config.headers.Authorization = `Bearer ${this.client.accessToken}`;
2025-01-28 15:39:30 +01:00
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
}
private setResponseInterceptor() {
this.http.interceptors.response.use(
(response) => {
return response;
},
async (error) => {
if (!error.config.url.includes("/admin")) {
return Promise.reject(error);
}
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;
2025-02-05 14:29:09 +01:00
return await this.client
.refreshToken()
2025-01-28 15:39:30 +01:00
.then(() => {
return this.http(originalRequest);
})
.catch(() => {});
}
return Promise.reject(error);
}
);
}
}