import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
|
|
import messageBoxService from './message-box.service';
|
|
const notRequireInterceptorErrorUrl = [
|
'/otp/verify',
|
// '/otp/sendOtp',
|
'/eService/authenticate',
|
'/login/validate/get_img_code',
|
'/login/validate/verify_img_code',
|
'/api/access_analysis/insert'
|
];
|
|
function getBaseUrl(): string {
|
const baseUrl = process.env.BASE_URL;
|
if (!baseUrl) {
|
throw new Error('BASE_URL is not defined in process.env');
|
}
|
// const pattern = /^(https?:\/\/)[\w.-]+(:\d+)?/i; // 更嚴格的URL驗證
|
// if (!pattern.test(baseUrl)) {
|
// throw new Error('Invalid BASE_URL');
|
// }
|
// 不需要再清理URL,因為它已經是絕對URL
|
return baseUrl;
|
}
|
export const http = axios.create({
|
baseURL: getBaseUrl(), // 使用函數動態獲取baseURL
|
withCredentials: true
|
});
|
|
let apiNumber = 0;
|
|
http.interceptors.request.use(
|
(config: AxiosRequestConfig) => {
|
apiNumber += 1;
|
loadingStart();
|
addHttpHeader(config);
|
return config;
|
}
|
);
|
|
http.interceptors.response.use(
|
(response: AxiosResponse) => {
|
apiNumber -= 1;
|
if (apiNumber === 0) {
|
loadingFinish();
|
}
|
return response;
|
},
|
(error: AxiosError) => {
|
apiNumber -= 1;
|
if (apiNumber === 0) {
|
loadingFinish();
|
}
|
showErrorMessageBox(error)
|
return Promise.reject(error);
|
}
|
);
|
|
function addHttpHeader(config: AxiosRequestConfig): void {
|
config.headers = {
|
Authorization: 'Bearer ' + localStorage.getItem('id_token'),
|
'content-type': 'application/json'
|
}
|
}
|
|
function loadingStart(): void {
|
setTimeout(() => {
|
window.$nuxt.$loading.start();
|
}, 0);
|
};
|
|
function loadingFinish(): void {
|
setTimeout(() => {
|
window.$nuxt.$loading.finish();
|
}, 0);
|
};
|
|
function showErrorMessageBox(error: any): void {
|
setTimeout(() => {
|
// NOTE: 此為 HOT FIX 顧問登入失敗後,會出現逾時的 dialog [Tomas, 2022/7/20 14:21]
|
if(error.config.url.includes('/eService/authenticate')) return;
|
if (error.config.url.includes('/otp/sendOtp')) {
|
messageBoxService.showErrorMessage('', error);
|
return
|
}
|
if (!notRequireInterceptorErrorUrl.includes(error.config.url)) {
|
switch (error.response.status) {
|
case 401:
|
Promise.all([messageBoxService.showErrorMessage('登入逾時'), window.$nuxt.$store.dispatch('localStorage/actionStorageClear')]).then(() => {
|
if (window.$nuxt.$route.name === 'index') {
|
location.reload();
|
} else {
|
window.$nuxt.$router.push('/');
|
}
|
});
|
break;
|
|
default:
|
messageBoxService.showErrorMessage('', error);
|
break;
|
}
|
}
|
}, 0)
|
};
|