UNPKG

gxd-vue-library

Version:

依赖与element Ui插件库,聚福宝福利PC端插件库

453 lines (399 loc) 12.8 kB
'use strict'; const settings = require('./../../settings'); const clog = require('./../../build/clog'); const delay = settings.apiDelay || 10000; import { baseCheckVarType, baseCloneDeep, baseEnvTypeReg } from "@/utils/xd.base"; import store from './../store'; const spUrlHandle = ['saas-admin']; import { getSiteIdFromCookie } from "@/utils/auth.js" /** * @description 检查是否需要开始上报日志与添加token参数 * @param config * @returns {boolean} true=>不开启 false=>开启 */ export const checkNotLogs = (config) => { let temp = false; settings.apiWhiteList.map(item => { let reg = new RegExp(item); if (reg.test(config.url)) temp = true }); return temp; }; /** * @description 异步请求出错上报日志 * @param response * @param startTime */ export const isUpdateLog = (response, startTime)=>{ //设置返回数据使用时间 let useTime = new Date().getTime() - startTime; //返回数据为数组或者对象进行序列化 let responseData = response.data; if (baseCheckVarType(responseData) === 'object' || baseCheckVarType(responseData) === 'array' ) { responseData = JSON.stringify(responseData); } let requestInfo = { type: 'ajax.error', url: response.config.url, useTime: `${useTime} ms`, status: response.status, method: response.config.method, params: baseCloneDeep(response.config['data'] || response.config['params'] || {}), code: `ajax.${response['status']}`, headers: response.config['headers'] || {}, response: responseData }; //不需要上传日志接口 if(checkNotLogs(response.config)){ return true } //接口超时上报日志 if(useTime > delay){ requestInfo['type'] = 'ajax.error.delay'; updateLog(requestInfo); clog(`Slow Link:${response.config.url} ${useTime} ms`, 'red'); return true } else{ clog(`Fast Link:${response.config.url} ${useTime} ms`, 'green'); } //401|403|200不上报日志 if (response['status'] === 401 || response['status'] === 200 || response['status'] === 403) { if (response.config.apiPath) { console.warn(`code:${response['status']},method:${response.config.method},apiUrl:${response.config.apiPath}`) } return true } //其他错误上报 updateLog(requestInfo); }; /** * @description 获取请求使用基础路径 * @param config {Object} */ export function getBaseApiUrl(config) { //登陆授权接口,项目配置,权限列表 let reg = /(\/api\/pb\/host\/get-brand|\/permission\/list|\/oauth\/company_login)/; if (reg.test(config.url)) { if (typeof $xdBrandInfo !== 'undefined' && $xdBrandInfo['api_host']) { config.url = `${$xdBrandInfo['api_host']}${config.url}`; } return } let host = window.location.host; let apiBaseUrl = settings.apiBaseUrl || 'http://sandbox-partners-apis.jufubao.cn'; //特殊处理(使用自己站点域名作为ApiBaseUrl)(正式环境) if(spUrlHandle.includes(settings.system) || settings.apiBaseUrl === 'location' ) { if(!baseEnvTypeReg.test(host)){ apiBaseUrl = `${window.location.protocol}//${window.location.host}`; console.warn(`master.sp.apiBaseUrl:${apiBaseUrl}`); } } let url = apiBaseUrl; //服务接口 config.url = `${url}${config.url}`; } /** * @description 设置公共参数 * @param config {Object} */ export function setCommonParams(config) { let reg = /(\/api\/pb\/host\/get-brand|\/permission\/list|\/oauth\/company_login)/; let commonParams = store.state.commonParams || {}; //设置公共参数 if (!reg.test(config.url)) { if (config.data) config.data = {...config.data, ...commonParams}; if (config.params) config.params = {...config.params, ...commonParams}; } } function getElementByIdStyle(id){ const el = document.getElementById(id); if(el){ if(el['currentStyle']) return el['currentStyle']; else return window.getComputedStyle(el,null) } return null } /** * @description 获取元素高度 * @param id {string} 元素ID * @param inner {boolean} true=>获取元素高度 false=>获取元素高度 + 边距高度 * @return {number} */ export function getHeight(id,inner=true) { if(id) { const el = getElementByIdStyle(id); if(!el) return 0; let height = 0; if(inner) height = parseInt(el.height); else{ let box = el.boxSizing; let elHeight = parseInt(el.height); let topPadding = parseInt(el['padding-top']); let bottomPadding = parseInt(el['padding-bottom']); let topMargin = parseInt(el['margin-top']); let bottomMargin = parseInt(el['margin-bottom']); if(box === 'border-box') topPadding = bottomPadding = 0; height = elHeight + topPadding + bottomPadding + topMargin + bottomMargin; } return height; } else return 0 } /** * @description 获取元素宽度 * @param id {string} 元素ID * @param inner {boolean} true=>获取元素宽度 false=>获取元素宽度 + 边距宽度 * @return {number} */ export function getWidth(id,inner=true) { if(id) { const el = getElementByIdStyle(id); if(!el) return 0; let width = 0; if(inner) width = parseInt(el.width); else{ let box = el.boxSizing; let elHeight = parseInt(el.width); let topPadding = parseInt(el['padding-left']); let bottomPadding = parseInt(el['padding-right']); let topMargin = parseInt(el['margin-left']); let bottomMargin = parseInt(el['margin-right']); if(box === 'border-box') topPadding = bottomPadding = 0; width = elHeight + topPadding + bottomPadding + topMargin + bottomMargin; } return width; } else return 0 } /** * @description 搜索到匹配关键字高亮处理 * @param str {string} 需要检索的字符串 * @param keyword {string|array} 搜索关键字 * @param options {Object} * @param options.tag {string} 有效的html中有效的tag标签 * @param options.color {string} 匹配的字符高亮颜色 默认:red * @param options.weight {string} * ,css font-weight有效值,默认:normal * @returns {string} */ export function strHigh(str, keyword, options = {}) { try { let __option = { tag: 'span', color: 'red', weight: 'normal', }; if (this.checkVarType(keyword) === 'array') { keyword = keyword.join('|'); } else if (this.checkVarType(keyword) === 'string') { keyword = keyword.trim(); } else { console.error('关键字类型错误'); return str; } let opt = Object.assign({}, __option, options); let reg = new RegExp(`(${keyword})`, 'ig'); return str.replace(reg, `<${opt.tag} style="color:${opt.color};font-weight: ${opt.weight}">$1</${opt.tag}>`); } catch (e) { console.error(e); return str; } } /** * @description 过滤html标签 * @param html {string} html文本 * @param allowed {string} 允许通过的标签 例如:'<p><a><li>' * @returns {string} */ export function filterHtml(html, allowed = '') { allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); let tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi; return html.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) { return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''; }); } //==请求参数,200状态, 错误提示统一处理======================== /** * @description 检查当前项目是不是加盟商 * @return {boolean} */ function isCheckPartner(){ let partner = false; //加盟商后台与应用中心 if(settings.system === 'partner' || settings.system === 'sms' ) partner = true; //以下面特定字符开头 let index = ['partner-', 'sms-', 'app-', 'oa-']; index.map(key=>{ if(settings.system.indexOf(key) === 0) { partner = true; } }); return partner; } /** * @description 检查是不是获取权限接口 * @param response */ function isCheckPermissionApi(response){ let permissionApi = false; //是不是特定的接口 let permission = '/idaas-auth/v1/menus-permission'; if(response.config.url.indexOf(permission) !== -1) { permissionApi = true; } return permissionApi } /** * @description 检查是否为素材相关接口 * @param config */ function isCheckMaterialApi(config){ let Api = false; //是不是特定的接口 let reg = '/material-api-'; if(config.url.indexOf(reg) !== -1) { Api = true; } return Api } /** * @description 检查当前项目是不是加盟商项目并且是不是获取权限接口 */ function isPartnerAndPermissionApi(response){ let isPartner = isCheckPartner(); let isPermissionApi = isCheckPermissionApi(response); let isPartnerCommon = true //是加盟商&&权限接口 if(isPermissionApi && isPartner) { if(response.config.params && response.config.params.isOtherPartner) { isPartnerCommon = false } } return isPermissionApi && isPartner && isPartnerCommon; } /** * @description 当前项目需要请求其他项目的权限值(主要正对加盟商相关系统) */ function getPermission(response){ return new Promise((resolve,reject)=>{ store.dispatch('getPermission', {project_id: 'partner-common', isOtherPartner: true}).then((res)=>{ console.warn('partner-common') response.data.permissions = (response.data.permissions||[]).concat(res.roles || []); resolve(response.data); }).catch(error=>{ resolve(response.data) }); }) } /** * @description 设置加盟商相关项目公共项目ID * @param config * @return {*} */ function setPartnerMaterialProjectId(config){ let commonProjectId = 'partner-common'; //设置项目ID if(config.headers && config.headers['X-Jfb-Project-Id']) config.headers['X-Jfb-Project-Id'] = commonProjectId; if(config.params && config.params.system) config.params.system = commonProjectId if(config.data && config.data.system) config.data.system = commonProjectId return config } /** * @description 接口地址中带有“/idaas-auth/”特殊字符,去掉:config.headers['X-Jfb-Project-Id'] * @param config * @return {{headers}|*} */ function isIdaasAuthToDelHeaders(config) { let spStr = '/idaas-auth/'; if(config.url.indexOf(spStr) !== -1 && 0) { if(config.headers && config.headers['X-Jfb-Project-Id']) { delete config.headers['X-Jfb-Project-Id'] } return config } return config } /** * @description 检查特定的链接是否在数组中 * @param checkArr {array} 指定的链接地址 * @param config {Object} * @return {boolean} */ function checkUrlIncludes(checkArr=[], config){ let temp = false; let len = checkArr.length; for (let i = 0; i < len; i++){ if(config.url.indexOf(checkArr[i]) !== -1) { temp = true; break } } return temp; } /** * @description 请求参数进行网关处理 * @param config {Object} * @return {*} */ export function handleRequestGateway(config){ //接口地址中带有“/idaas-auth/”特殊字符,去掉:config.headers['X-Jfb-Project-Id'] config = isIdaasAuthToDelHeaders(config); //商城&&电影后台获取权限接口,添加站点ID参数 if(checkUrlIncludes(['/idaas-auth/v1/menus-permission'],config) && ['partner-mall','partner-movie'].includes(config.params.system) ){ if(config.params) config.params.site_id = getSiteIdFromCookie() } //获取json文件不传headers不传cookie let reg = /^.+(\/common\/).+(\.json)$/; if(reg.test(config.url)) { if(config.headers) { config.headers = {}; config.withCredentials = false; } } //检查当前请求接口是否为素材相关接口特殊处理 //解决素材库在加盟商下授权公共权限太多问题 if(isCheckPartner() && isCheckMaterialApi(config)) { return setPartnerMaterialProjectId(config); } return config; } /** * @description 请求返回200处理 * @param response * @return {Promise<Awaited<unknown>>} */ export function handleResponseSuccessGateway(response){ //检查当前项目是不是加盟商项目|获取权限接口(原接口) //解决素材库在加盟商下授权公共权限太多问题 if(isPartnerAndPermissionApi(response)) { return getPermission(response) } return Promise.resolve(response.data) } /** * @description 请求非200状态提示公共处理 * @param response 数据返回对象 * @param Message {Element} */ export function handleResponseErrorGateway(response, Message){ Message({ message: response.data.message || 'Error', type: 'error', duration: 2 * 1000, showClose: true, }); } //==请求参数,200状态, 错误提示统一处理========================