frequi_origin/src/shared/apiService.ts

81 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-04-19 18:26:42 +00:00
import { useBotStore } from '@/stores/ftbotwrapper';
import axios, { AxiosHeaders } from 'axios';
2021-08-28 13:40:39 +00:00
import { UserService } from './userService';
2021-08-31 18:30:19 +00:00
export function useApi(userService: UserService, botId: string) {
2021-08-28 13:40:39 +00:00
const api = axios.create({
baseURL: userService.getBaseUrl(),
timeout: 20000,
2021-08-28 13:40:39 +00:00
withCredentials: true,
});
// Sent auth headers interceptor
2020-07-24 05:21:32 +00:00
api.interceptors.request.use(
(request) => {
2020-07-24 05:21:32 +00:00
const token = userService.getAccessToken();
try {
if (token) {
request.headers = request.headers as AxiosHeaders;
// Append token to each request
request.headers.set('Authorization', `Bearer ${token}`);
}
} catch (e) {
console.log(e);
2020-07-24 05:21:32 +00:00
}
return request;
2020-07-24 05:21:32 +00:00
},
(error) => Promise.reject(error),
);
2020-07-24 05:21:32 +00:00
api.interceptors.response.use(
(response) => response,
(err) => {
2021-06-20 18:02:47 +00:00
// console.log(err);
2020-07-24 05:21:32 +00:00
if (err.response && err.response.status === 401) {
2022-04-28 04:46:22 +00:00
console.log('Fetching refresh_token...');
2020-07-24 05:21:32 +00:00
return userService
.refreshToken()
.then((token) => {
// Retry original request with new token
const { config } = err;
config.headers.Authorization = `Bearer ${token}`;
2020-07-24 05:21:32 +00:00
return new Promise((resolve, reject) => {
axios
.request(config)
.then((response) => {
resolve(response);
})
.catch((error) => {
reject(error);
});
});
})
.catch((error) => {
console.log('No new token received');
console.log(error);
2022-12-08 18:54:43 +00:00
const botStore = useBotStore();
if (botStore.botStores[botId]) {
botStore.botStores[botId].setIsBotOnline(false);
botStore.botStores[botId].isBotLoggedIn = false;
}
});
2020-07-24 05:21:32 +00:00
// maybe redirect to /login if needed !
}
if ((err.response && err.response.status === 500) || err.message === 'Network Error') {
2021-06-20 18:02:47 +00:00
console.log('Bot not running...');
2022-04-19 18:26:42 +00:00
const botStore = useBotStore();
botStore.botStores[botId]?.setIsBotOnline(false);
2020-07-24 05:21:32 +00:00
}
2021-06-20 18:02:47 +00:00
2020-07-24 05:21:32 +00:00
return new Promise((resolve, reject) => {
reject(err);
});
},
);
2020-05-20 05:19:14 +00:00
2021-08-28 13:40:39 +00:00
return {
api,
};
2020-05-20 05:19:14 +00:00
}