以前我寫了一篇文章,分享了本身的項目中對於接口管理的方法。總結下來就是:定義接口文件--withAxios導出--調用接口方法。這樣實現了接口的統一管理和調用接口的語義化與簡單化。html
根據在項目的使用,發現有如下問題須要優化:ios
根據以上問題,採用瞭如下解決方案:typescript
經過代碼展現一下(React項目):redux
service.tsaxios
import { IApiItem } from '@/configs/api/declares'; import withAxios from '@/utils/withAxios'; const api: IApiItem[] = [ { name: 'getSummary', url: 'http://xx:8000/api/getSummary' }, { name: 'getDetail', url: 'http://xx:8000/api/getDetail' }, { name: 'getDetailChildren', url: 'http://xx:8000/api/getDetailChildren' }, { name: 'getCurrentUser', url: 'http://xx:8000/api/getCurrentUser' }, ]; interface IProdMonitorApi { getSummary: any; getDetail: any; getDetailChildren: any; getCurrentUser: any; } export default withAxios<IProdMonitorApi>(api);
withAxios.ts後端
function withAxios<T>(apiConfig: IApiItem[], usePassportOrigin: boolean = false): T { const serviceMap = {} as T; apiConfig.map(({ name, url, method = 'get', ...rest }: IApiItem) => { return (serviceMap[name] = async function(data = {}) { if (serviceMap[`${name}Cancel`] && typeof serviceMap[`${name}Cancel`] === 'function') { serviceMap[`${name}Cancel`](); } const source = axios.CancelToken.source(); serviceMap[`${name}Cancel`] = () => { source.cancel(`已取消上次未完成請求:${name}`); }; rest.cancelToken = source.token; let key = 'params'; const apiMethod = method.toLowerCase(); if (apiMethod === 'post' || apiMethod === 'put') { key = 'data'; } let fetchUrl = url; if (url.indexOf('http') !== 0) { fetchUrl = usePassportOrigin ? NetworkUtils.passportOrigin + url : NetworkUtils.serverOrigin + url; } return axios({ method, url: fetchUrl, [key]: data, fetchName: name, ...rest, } as AxiosRequestConfig); }); }); return serviceMap; } export default withAxios;
在須要使用接口的地方:api
import Service from "./service.ts"
Service.getSummary(requestParams).then(...)
說明:async