import axios from 'axios' import { Message, MessageBox, Loading } from 'element-ui' import router from '../router' import i18n from '../lang' import { env } from '../services/global' import { toSentenceCase } from '../utils/services' let loadingInstance: any const multiMessageTimeout = 500 let previousErrorMessage: string let previousSuccessMessage: string let service = axios.create({ baseURL: getServerPath(), // timeout: 5000 withCredentials: true // send cookies when cross-domain requests }) export function getServerPath() { const address = localStorage.getItem('address') return address || process.env.VUE_APP_BASE_API // url = base url + request url } init() function init() { // Request interceptors service.interceptors.request.use( (config: any) => { // Add X-Access-Token header to every request, you can add other custom headers here // if (UserModule.token) { // config.headers['X-Access-Token'] = UserModule.token // } // const token = getToken() // if (token) { // config.headers.Authorization = `Bearer ${token}` // } // if (config.url.includes('/check_code') && config.method === 'post') { // const tempToken = getTempToken() // if (tempToken) { // config.headers.Authorization = `Bearer ${tempToken}` // } // } // if ( // (config.url.includes('/reset') || config.url.includes('/invite')) && // config.method === 'post' // ) { // const tempToken = getTempToken() // if (tempToken) { // config.headers.Authorization = `Bearer ${tempToken}` // } // } // for local debug if (config.baseURL.includes('127.0.0.1')) { config = replaceUrl(config, ':3333', ':3334') } if (env() === 'QA') { config = replaceUrl(config, '_qa_cms', '_qa_dams') } else if (env() === 'UAT') { config = replaceUrl(config, '_uat_cms', '_uat_dams') } return config }, (error) => { Promise.reject(error) } ) // Response interceptors service.interceptors.response.use( async(response) => { const res = response.config.responseType === 'blob' ? response : response.data if (res.status !== 200 && res.status !== 201) { await catchError(response) return Promise.reject(response) } else { return res } }, async(error) => { await catchError(error) return Promise.reject(error) } ) } function replaceUrl(config: any, cms: string, dams: string) { let url = '' if (config.url.includes('_dev_cms')) { url = config.url.replace('_dev_cms', cms) } else if (config.url.includes('_dev_dams')) { url = config.url.replace('_dev_dams', dams) } if (url) { config.url = config.baseURL + url config.baseURL = '' } return config } async function catchError(error: any) { removeLoading() let message try { if (error.response.data instanceof Blob) { // to handle error throw by excel API // read blob return response error.response.data = await readErrorBlobAndConvertBack( error.response.data ) } } catch (e) { } let err if (error.response) { if (error.response?.config?.url.includes('fe_log')) { return } err = error.response.data } else { err = error.data } try { if (err.message) { if (typeof err.message === 'object') { message = err.message.message || err.message.sqlMessage if (!message) { if ('response' in err.message) { message = err.message.response.message } } } else { message = err.message } } } catch (e) { // console.log(e) } // try to catch validation errors try { if (err.data.response.message && err.data.response.message.length) { const messages = err.data.response.message if (Array.isArray(messages)) { message = '' for (const m of messages) { message += toSentenceCase(m) + '.
' } } } } catch (e) { // console.log(e) } const isLogoutApi = error.response?.config?.url.includes('/logout') // using previous message to check // to prevent duplicate error shown at the same time if (message !== previousErrorMessage) { previousErrorMessage = message MessageBox.confirm(message, i18n.t('general.warning') as string, { confirmButtonText: i18n.t('general.ok') as string, showCancelButton: false, dangerouslyUseHTMLString: true, type: 'warning' }) } setTimeout(() => { previousErrorMessage = '' }, multiMessageTimeout) } async function readErrorBlobAndConvertBack(error: any) { return new Promise((resolve) => { const reader: any = new FileReader() reader.addEventListener('loadend', () => { resolve(JSON.parse(reader.result)) }) reader.readAsText(error) }) } export default service export function reinit(address: string) { if (address) { service = axios.create({ baseURL: address }) init() } } // if the data is a form data, ensure that isFormData is set to true // if the data is a blob data, ensure that isBlob is set to true export function http( httpType: 'get' | 'post' | 'put' | 'delete', url: string, data: any = {}, isMessage = false, isLoading = false, isFormData = false, isBlob = false, returnError = false ) { let body: any if (isLoading) { showLoading() } if (isFormData) { body = data } else { body = data if (typeof body === 'object') { for (const b in body) { if (b === 'search_str') { continue } if (b === 'other_params') { for (const o in body[b]) { if ( (typeof body[b][o] === 'string' && !body[b][o]) || (Array.isArray(body[b][o]) && !body[b][o].length) ) { delete body[b][o] } } break } } } } return service({ url: url, method: httpType, responseType: isBlob ? 'blob' : 'json', data: body }) .then((response: any) => { if (isLoading) { removeLoading() } if (isMessage) { const message = response.message || i18n.t('general.success') if (message !== previousSuccessMessage) { previousSuccessMessage = message Message({ message: message, type: 'success', duration: 2 * 1000, dangerouslyUseHTMLString: true }) } setTimeout(() => { previousSuccessMessage = '' }, multiMessageTimeout) } let r = response if (!isBlob) { r = response.data } return r }) .catch((error: any) => { removeLoading() if (returnError) { try { return error.response.data || error } catch (err) { } } else { return false } }) } export function forkHttp(list: any = [], isLoading = false) { if (list && list.length) { if (isLoading) { showLoading() } const apiCalls: any = [] for (const l of list) { apiCalls.push(l) } return axios .all(apiCalls) .then((response: any) => { if (isLoading) { removeLoading() } return response }) .catch(() => { removeLoading() return false }) } } let loadingCounter = 0 export function showLoading() { loadingCounter++ loadingInstance = Loading.service({ fullscreen: true, customClass: 'custom-fullscreen-loading', text: `${i18n.t('general.pleaseWait')}` }) } export function removeLoading(hardRemove = false) { loadingCounter-- if (loadingInstance) { if (loadingCounter <= 0) { loadingCounter = 0 setTimeout(() => { loadingInstance.close() }, 200) } if (hardRemove) { loadingCounter = 0 loadingInstance.close() } } }