frequi_origin/src/shared/apiService.ts

85 lines
2.2 KiB
TypeScript
Raw Normal View History

import axios from 'axios';
2021-08-28 13:40:39 +00:00
import { UserService } from './userService';
2020-07-24 05:21:32 +00:00
/**
2021-08-28 13:40:39 +00:00
* Global store variable - keep a reference here to be able to emmit alerts
2020-07-24 05:21:32 +00:00
*/
2021-08-28 13:40:39 +00:00
let globalStore;
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...');
2021-08-31 18:30:19 +00:00
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
}
2020-06-22 18:18:45 +00:00
2021-08-28 13:40:39 +00:00
/**
* Initialize api so store is accessible.
* @param store Vuex store
*/
export function initApi(store) {
globalStore = store;
//
}