保誠-保戶業務員媒合平台
jack
2023-09-05 3ecee0fa557b7bb9e83b67e289b316f04efa9ce5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import { AxiosRequestConfig, AxiosError, AxiosResponse} from 'axios';
import axios from 'axios';
import _ from 'lodash';
 
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'
];
 
const BASE_URL = process.env.BASE_URL!;
 
function sanitizeBaseUrl(baseUrl: string): string {
  const isValidBaseUrl = (url: string) => url.includes('api');
  if (isValidBaseUrl(baseUrl)) {
    return baseUrl;
  } else {
    throw new Error('Invalid BASE_URL');
  }
}
 
export const http = axios.create({
  baseURL: sanitizeBaseUrl(BASE_URL),
  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 (!_.includes(notRequireInterceptorErrorUrl, error.config.url)) {
      switch (error.response.status) {
        case 401:
          Promise.all([messageBoxService.showErrorMessage('登入逾時'), window.$nuxt.$store.dispatch('localStorage/actionStorageClear')]).then(() => {
            _.isEqual(window.$nuxt.$route.name, 'index') ? location.reload() : window.$nuxt.$router.push('/');
          });
          break;
 
        default:
          messageBoxService.showErrorMessage('', error);
          break;
      }
    }
  }, 0)
};