以前我写了一篇文章,分享了本身的项目中对于接口管理的方法。总结下来就是:定义接口文件--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