保誠-保戶業務員媒合平台
劉鈞霖
2021-12-15 8920cf32b364d6018da3a866e24e8d39e3b86087
PAMapp/assets/ts/api/share.ts
@@ -1,31 +1,67 @@
import { AxiosRequestConfig, AxiosError, AxiosResponse} from 'axios';
import ErrorMessageBox from '../errorService';
import axios from 'axios';
import { AxiosRequestConfig, AxiosError, AxiosResponse } from 'axios';
import _ from 'lodash';
const notRequireInterceptorErrorUrl = [
  '/otp/verify',
  '/eService/authenticate',
  '/login/validate/get_img_code',
  '/login/validate/verify_img_code',
];
export const service = axios.create({
    baseURL: process.env.BASE_URL
})
  baseURL: process.env.BASE_URL,
  withCredentials: true
});
service.interceptors.request.use(function (config: AxiosRequestConfig) {
  loadingStart();
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    loadingStart();
    addHttpHeader(config);
    return config;
}, function (error: AxiosError) {
  loadingFinish();
    return Promise.reject(error);
});
  }
);
service.interceptors.response.use(function (response: AxiosResponse) {
  loadingFinish();
service.interceptors.response.use(
  (response: AxiosResponse) => {
    loadingFinish();
    return response;
}, function (error: AxiosError) {
  loadingFinish();
  },
  (error: AxiosError) => {
    loadingFinish();
    showErrorMessageBox(error)
    return Promise.reject(error);
});
  }
);
function addHttpHeader(config: AxiosRequestConfig): void {
  config.headers = {
    Authorization: 'Bearer ' + localStorage.getItem('id_token')
  }
}
function loadingStart(): void {
  setTimeout(() => {
    window.$nuxt.$loading.start();
  });
}
  window.$nuxt.$loading.start();
};
function loadingFinish(): void {
    window.$nuxt.$loading.finish();
}
  window.$nuxt.$loading.finish();
};
function showErrorMessageBox(error: any): void {
  // console.log('error', error, error.response);
  if (!_.includes(notRequireInterceptorErrorUrl, error.config.url)) {
    switch (error.response.status) {
      case 401:
        Promise.all([ErrorMessageBox('登入逾時'),window.$nuxt.$store.dispatch('localStorage.service/clearStorage')]).then(()=>{
          _.isEqual(window.$nuxt.$route.name, 'index') ? location.reload() : window.$nuxt.$router.push('/');
        });
        break;
      default:
        ErrorMessageBox('', error);
        break;
    }
  }
};