frequi_origin/src/shared/apiService.ts

73 lines
2.0 KiB
TypeScript
Raw Normal View History

2022-04-19 18:26:42 +00:00
import { useBotStore } from '@/stores/ftbotwrapper';
import axios 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: 10000,
withCredentials: true,
});
// Sent auth headers interceptor
2020-07-24 05:21:32 +00:00
api.interceptors.request.use(
(config) => {
const custconfig = config;
const token = userService.getAccessToken();
// Append token to each request
if (token) {
// Merge custconfig dicts
custconfig.headers = { ...config.headers, ...{ Authorization: `Bearer ${token}` } };
}
return custconfig;
},
(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) {
console.log('Dispatching refresh_token...');
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);
});
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
}