87 lines
2.2 KiB
TypeScript
87 lines
2.2 KiB
TypeScript
|
import axios, { AxiosInstance } from "axios";
|
||
|
import { WebApiClient } from ".";
|
||
|
|
||
|
export default class http {
|
||
|
public http: AxiosInstance;
|
||
|
private host: WebApiClient;
|
||
|
|
||
|
constructor(host: WebApiClient) {
|
||
|
this.host = host;
|
||
|
this.http = axios.create({
|
||
|
baseURL: this.host.accessToken + "/api",
|
||
|
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 == "") {
|
||
|
config.headers.Authorization = `Bearer ${this.host.accessToken}`;
|
||
|
}
|
||
|
|
||
|
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;
|
||
|
return await this.refreshToken()
|
||
|
.then(() => {
|
||
|
return this.http(originalRequest);
|
||
|
})
|
||
|
.catch(() => {});
|
||
|
}
|
||
|
|
||
|
return Promise.reject(error);
|
||
|
}
|
||
|
);
|
||
|
}
|
||
|
|
||
|
private refreshToken(): Promise<void> {
|
||
|
return new Promise<void>(async (resolve, reject) => {
|
||
|
await this.http
|
||
|
.get(`/webapi/retrieve`, {
|
||
|
headers: {
|
||
|
Authorization: `Bearer ${this.host.webapiToken}`,
|
||
|
},
|
||
|
})
|
||
|
.then(async (response) => {
|
||
|
const { accessToken } = response.data;
|
||
|
|
||
|
this.host.setAccessToken(accessToken);
|
||
|
|
||
|
resolve();
|
||
|
})
|
||
|
.catch((error) => {
|
||
|
console.error("Error refreshing webapi token:", error);
|
||
|
reject("failed token retrieve");
|
||
|
});
|
||
|
});
|
||
|
}
|
||
|
}
|