保誠-保戶業務員媒合平台
Tomas
2023-09-05 0de81c2b3f56f57121f6a9f911c599cef70eeeb2
PAMapp/shared/services/httpClient.ts
@@ -6,18 +6,40 @@
const notRequireInterceptorErrorUrl = [
  '/otp/verify',
  // '/otp/sendOtp',
  '/eService/authenticate',
  '/login/validate/get_img_code',
  '/login/validate/verify_img_code',
  '/api/access_analysis/insert'
];
const BASE_URL = process.env.BASE_URL!;
function sanitizeBaseUrl(baseUrl: string): string {
  const pattern = /^(https?:\/\/).+/i;
  if (!pattern.test(baseUrl)) {
    throw new Error('Invalid BASE_URL');
  }
  const cleanedBaseUrl = cleanUrl(baseUrl);
  return cleanedBaseUrl;
}
function cleanUrl(url: string): string {
  const cleanedUrl = url.replace(/[^a-zA-Z0-9:/._-]/g, '');
  return cleanedUrl;
}
export const http = axios.create({
  baseURL: process.env.BASE_URL,
  baseURL: sanitizeBaseUrl(BASE_URL),
  withCredentials: true
});
let apiNumber = 0;
http.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    apiNumber += 1;
    loadingStart();
    addHttpHeader(config);
    return config;
@@ -26,11 +48,17 @@
http.interceptors.response.use(
  (response: AxiosResponse) => {
    loadingFinish();
    apiNumber -= 1;
    if (apiNumber === 0) {
      loadingFinish();
    }
    return response;
  },
  (error: AxiosError) => {
    loadingFinish();
    apiNumber -= 1;
    if (apiNumber === 0) {
      loadingFinish();
    }
    showErrorMessageBox(error)
    return Promise.reject(error);
  }
@@ -38,7 +66,8 @@
function addHttpHeader(config: AxiosRequestConfig): void {
  config.headers = {
    Authorization: 'Bearer ' + localStorage.getItem('id_token')
    Authorization: 'Bearer ' + localStorage.getItem('id_token'),
    'content-type': 'application/json'
  }
}
@@ -55,8 +84,13 @@
};
function showErrorMessageBox(error: any): void {
  // console.log('error', error, error.response);
  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 (!_.includes(notRequireInterceptorErrorUrl, error.config.url)) {
      switch (error.response.status) {
        case 401: