这两天遇到一个需求,需要给项目中使用的公共接口,在调用的地方,请求头headers里加一个model 参数。
一开始就在封装接口的地方添加,添加了几个之后,发现太费时费力了,项目中大概将近200 个公共接口,加的时候要仔细加,要精确的找准每一处需要添加的地方,为了不影响其他地方的调用,最好复制封装的接口,不过这个方案被否定了,很多冗余的封装接口着实没有必要。
接着有伙伴提出就对封装公共接口的方法传参,headers 里的model值取当前页面的路由hash,在页面调用的地方把取到的路由hash作为参数传进去。
不过还是很耗时耗力,经过研究,同事给出了一个很好的思路,在全局封装请求的方法里,统一处理,这个方法不仅高效,而且不容易漏加和错加,下面是梳理过程:
1.把公共接口写成一个json文件白名单,我这边在src下面的assets下面新建json文件夹,里面建commonInterface.json
文件内容:
[
{ "url": "/analysis/queryDocumentProcessizeDegreeLineChart" },
{ "url": "/application/queryCopy" },
{ "url": "/attach/download" },
{ "url": "/attach/upload" },
{ "url": "/basBpmUserChange/query" },
{ "url": "/basBpmUserChange/save" },
{ "url": "/bpm/agent/batch-delete" },
{ "url": "/bpm/agent/delete" },
{ "url": "/bpm/agent/query" },
{ "url": "/bpm/agent/save" },
{ "url": "/bpm/collection/quick-query" },
{ "url": "/bpm/createnav/initiate-list" },
{ "url": "/bpm/createnav/query" },
{ "url": "/bpm/linkProject/query" },
{ "url": "/bpm/pass-read/passread" },
{ "url": "/bpm/process/manage/withDrawInstance" },
{ "url": "/bpm/processquery/v2/mySponsor" },
{ "url": "/bpm/processquery/v2/processManage" },
{ "url": "/bpm/processquery/v2/tracking" },
{ "url": "/bpm/processversion/quickQuery" },
{ "url": "/bpm/productRelease/manage/deleteProductReleaseInfo" },
{ "url": "/bpm/urge" },
{ "url": "/businessrule/attribute/quickquery" },
{ "url": "/businessRuleAuth/batchDelete" },
{ "url": "/businessRuleAuth/delete" },
{ "url": "/businessRuleAuth/getAllTree" },
{ "url": "/businessRuleAuth/queryList" },
{ "url": "/businessRuleAuth/saveOrUpdate" },
{ "url": "/businessRuleAuth/updateState" },
{ "url": "/businessRuleManage/dele" },
{ "url": "/businessRuleManage/deleteReplace" },
{ "url": "/businessRuleManage/duplicateRule" },
{ "url": "/businessRuleManage/export-brs" },
{ "url": "/businessRuleManage/exportReplace" },
{ "url": "/businessRuleManage/getBusinessRuleDetail" },
{ "url": "/businessRuleManage/getReplace" },
{ "url": "/businessRuleManage/import-brs" },
{ "url": "/businessRuleManage/preview-brs" },
{ "url": "/businessRuleManage/queryList" },
{ "url": "/businessRuleManage/replace" },
{ "url": "/businessRuleManage/saveBtType" },
{ "url": "/businessRuleManage/saveBusinessRule" },
{ "url": "/datadictionary/getDictionaryOption" },
{ "url": "/datamanage/dataImport" },
{ "url": "/document/print" },
{ "url": "/document-modeling/getCopy" },
{ "url": "/electronicSignature/download" },
{ "url": "/foldertree/deleteCopy" },
{ "url": "/foldertree/saveCopy" },
{ "url": "/mangercenterdoc/uploadCopy" },
{ "url": "/modelapprove/query" },
{ "url": "/modellist/getUserRoleNameCopy" },
{ "url": "/modellist/queryKpiInBase" },
{ "url": "/modellistjson/ZCGetJson" },
{ "url": "/modellistjsonname/query" },
{ "url": "/modelResponsibility/getPosts" },
{ "url": "/modeltree/getTreeNodeWithoutAuthCopy" },
{ "url": "/om/getKpiIndexNum" },
{ "url": "/om/getProcessEfficiency" },
{ "url": "/om/getProcessUtilization" },
{ "url": "/om/getRiskIndexNum" },
{ "url": "/org/info/query" },
{ "url": "/org/manager/findOrgUsers" },
{ "url": "/org/tree/deleteTree" },
{ "url": "/org/tree/getAllRootTree" },
{ "url": "/process/analysis/postAverageTime" },
{ "url": "/processModel/getBusinessRuleAllTree" },
{ "url": "/processModel/getModelTree" },
{ "url": "/processNodeConfig/saveProcessField" },
{ "url": "/processPermissions/delete" },
{ "url": "/processPermissions/deleteList" },
{ "url": "/processPermissions/query" },
{ "url": "/processPermissions/save" },
{ "url": "/regulation/download" },
{ "url": "/regulation/getRegulationFolderCopy" },
{ "url": "/regulation/queryCopy" },
{ "url": "/regulation/queryReleasedCopy" },
{ "url": "/regulation/queryReleasedel" },
{ "url": "/regulation/save2Copy" },
{ "url": "/regulation/upload" },
{ "url": "/repositorybo/getRepositoryboFolder" },
{ "url": "/repositorybo/page" },
{ "url": "/select/user/cqp/getTotalOrgByNameCopy" },
{ "url": "/select/user/cqp/getTotalOrgCopy" },
{ "url": "/service/getHomePegeContent" },
{ "url": "/subjectrule/batchsave" },
{ "url": "/systemAuditManger/getDetailByOrgid" },
{ "url": "/systemChapterRelation/getTree" },
{ "url": "/systemManagement/getHistory" },
{ "url": "/systemManagement/getInterList" },
{ "url": "/test/automatic/batch-delete" },
{ "url": "/test/automatic/delete" },
{ "url": "/test/automatic/query" },
{ "url": "/test/automatic/run-test" },
{ "url": "/test/automatic/test-record-list" },
{ "url": "/vckpi/queryTreeD2D/" },
{ "url": "/frameVersion/getTreeNode" }
]
这里就像一个小型的数据库,里面所有的数据都是公共接口,里面每一个接口在页面很多地方调用2次或多次。
2.接着,在utils文件夹里,新建一个baseFetch.js,作为一个工具函数,里面封装公共接口传参方法:
// 封装 公共接口 headers 里传model参数
import store from '@/store'
// 获取公共接口白名单
const commonInterface=require('../assets/json/commonInterface.json')
const addModelUrl=(currentRequest)=>{
// 存储当前页面的hash值
store.commit('app/setCommonInterface', window.location.hash.slice(1))
// model 公共参数
let modelInterface=''
modelInterface=localStorage.getItem('CommonInterface')
// 前面没有 / 的request.url 处理为/
let newRequestUrl=currentRequest.url?currentRequest.url:''
if(newRequestUrl[0]!='/'){
newRequestUrl='/'+newRequestUrl
}
// 请求的接口和公共接口白名单对比
for (let index = 0; index < commonInterface.length; index++) {
const element = commonInterface[index];
if(newRequestUrl.includes(element.url)){
// 对比上就是公共接口 给headers加model 参数
currentRequest.headers['model'] =modelInterface?modelInterface:''
}
}2
}
export {addModelUrl}
3.补充一点,modelInterface实际上就是取的当前页路由 hash,存到vuex中,也存到localStorage中,vuex的存写法:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
let store = new Vuex.Store({
// 1. state
state:{
commonInterface:localStorage.getItem('CommonInterface')||'',//当前页面的hash
},
// 2. mutations
mutations:{
// state指的是state的数据
// payload传递过来的数据
// 当前页面的hash
setCommonInterface(state,payload){
localStorage.setItem('CommonInterface',JSON.stringify(payload))
state.commonInterface = payload
}
}
});
export default store;
4.在全局封装的请求方法的地方调用:
import { addModelUrl } from '../utils/baseFetch'
service.interceptors.request.use(request => {
// 调用公共传model 参数方法
addModelUrl(request)
localStorage.setItem('baseURL', process.env.VUE_APP_BASE_URL)
const { id } = store.state.app.userInfo
const token = localStorage.getItem('sxToken')
if (token) {
request.headers.token = token
}
if (id) {
request.headers.Pragma = 'no-cache'
request.headers['Cache-Control'] = 'no-cache, no-store'
if (request.method !== 'post') {
if (!request.params) {
request.params = {}
}
} else {
if (request.toast === undefined) {
request.toast = true
}
if (!request.data) {
request.data = {}
}
}
}
return request
})
在页面的效果:
这样就加好了,高效准确,很感谢同事的建议,以后自己遇到问题也要多思考,多想想最优方案,让自己成为更好的自己,不断鞭策自己,不断挑战,不断进步~~~~~~~~~