2020-05-16 08:52:26 +00:00
|
|
|
import axios from 'axios';
|
2021-08-28 13:40:39 +00:00
|
|
|
import { UserService } from './userService';
|
2020-05-16 08:52:26 +00:00
|
|
|
|
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-05-16 08:52:26 +00:00
|
|
|
|
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-17 05:09:52 +00:00
|
|
|
|
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-17 05:09:52 +00:00
|
|
|
});
|
|
|
|
|
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:24:14 +00:00
|
|
|
//TODO: pinia alternative
|
|
|
|
// globalStore.dispatch(`ftbot/${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
|
|
|
}
|