import BSL from 'bsl-core/typings'; import { isHttp } from 'bsl-core/utils/lang'; import App from '../typings/app'; import { getGlobalData } from '../utils/globalData'; type Method = ( | 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS' | 'post' | 'POST' | 'put' | 'PUT' | 'patch' | 'PATCH' ); type OmitRequestOption = Omit; export interface Cancel { current: WechatMiniprogram.RequestTask | null; } /** 放在app.globalData中的全局默认请求参数 */ export interface RequestConfig { __request__: { baseUrl: string; defaultData?: Record | null; header?: Record transformResponse: Option['transformResponse']; } } export interface Option extends OmitRequestOption { /** 请求接口的名称 */ api: string; /** * @param app | 整个应用生命周期内缓存 * @param page | 页面生命周期内缓存 */ cache?: 'app' | 'page'; method?: Method; // /** // * @default 'GET' // */ // method?: Method; transformResponse?: (data: any) => Promise>; } interface Cache { type: 'app' | 'page'; data: BSL.Response; } export const cacheData: Map = new Map(); export const clearCache = (key: string) => cacheData.delete(key); function request(): [(option: Option) => Promise>, Cancel, { current: string }] { const cancelToken: Cancel = { current: null }; const keyRef: { current: string } = { current: '' }; const request = (option: Option): Promise> => { return new Promise((resolve, reject) => { const { api } = option; const createKey = () => JSON.stringify({ api: option.api, data: option.data }); const method = (option.method || 'get').toLocaleUpperCase() as WechatMiniprogram.RequestOption['method']; const globalData = getGlobalData().__request__; const defualtData = globalData.defaultData; const postData: Record = {}; const isDataArray = Array.isArray(option.data); // 兼容有些手机url不自动转码 const urlStr = isHttp(api) ? api : encodeURI(globalData.baseUrl + api); // 判断是否有缓存 if (option.cache) { keyRef.current = createKey(); if (cacheData.has(keyRef.current)) { resolve(cacheData.get(keyRef.current)!.data); return; } } if (defualtData && isDataArray === false) { Object.keys((defualtData)).forEach((key) => { postData[key] = defualtData[key]; }); } // 去除object中值为undefined的字段 if (option.data && isDataArray === false) { Object.keys((option.data)).forEach((key) => { const data = option.data as Record; if (data[key] !== undefined) { postData[key] = data[key]; } }); } cancelToken.current = wx.request({ ...option, header: { ...globalData.header, ...option.header }, data: isDataArray ? option.data : postData, url: urlStr, method, success: async (res: WechatMiniprogram.RequestSuccessCallbackResult) => { if (res.statusCode === 200) { let key: string | undefined; // 判断接口是否需要缓存,并将结果储存起来 const data = res.data as BSL.Response; if (option.cache && data.code === 200) { key = createKey(); cacheData.set(key, { type: option.cache, data: data }); } const responseData = await (option.transformResponse || globalData.transformResponse)!(res.data); resolve({ ...responseData, cacheKey: key, source: res.data }); } else { const response: BSL.Response = { data: null, code: 500, msg: '网络错误', source: res.data }; resolve(response); } }, fail(e) { const message = e.errMsg; if (message === 'request:fail abort') { return; } reject(e); throw e; } }); }); }; return [request, cancelToken, keyRef]; } export default request;