frequi_origin/src/shared/apiService.ts

83 lines
2.3 KiB
TypeScript
Raw Normal View History

import axios from 'axios';
import userService from './userService';
2020-05-20 05:19:14 +00:00
export const api = axios.create({
2020-06-23 18:38:02 +00:00
baseURL: userService.apiBase,
2021-04-18 07:33:41 +00:00
timeout: 10000,
withCredentials: true,
2020-05-18 18:49:30 +00:00
});
2020-07-24 05:21:32 +00:00
/**
* Initialize api so store is accessible.
* @param store Vuex store
*/
export function init(store) {
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) => {
console.log(err);
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') {
console.log('Bot seems to be offline...');
store.dispatch('setIsBotOnline', false);
}
return new Promise((resolve, reject) => {
reject(err);
});
},
);
}
2020-05-20 05:19:14 +00:00
2020-06-22 18:18:45 +00:00
export function setBaseUrl(baseURL: string) {
2020-05-20 05:19:14 +00:00
if (baseURL === null) {
// Reset to "local" baseurl
2020-06-23 18:38:02 +00:00
api.defaults.baseURL = userService.apiBase;
} else if (!baseURL.endsWith(userService.apiBase)) {
api.defaults.baseURL = `${baseURL}${userService.apiBase}`;
2020-05-20 05:19:14 +00:00
} else {
2020-06-23 18:38:02 +00:00
api.defaults.baseURL = `${baseURL}${userService.apiBase}`;
2020-05-20 05:19:14 +00:00
}
}
2020-06-22 18:18:45 +00:00
setBaseUrl(userService.getAPIUrl());