import {pathJoin} from "@peryl/utils/pathJoin"; import {PlainObject} from "@peryl/utils/event"; import qs from "qs"; /** * 拦截ajax请求,模拟数据mock * @author 韦胜健 * @date 2024/5/6 14:34 */ export function createRequestInterceptor({ baseURL }: { baseURL?: string }) { baseURL = pathJoin(baseURL, '/'); const requestInterceptors: iRequestInterceptor[] = []; /*拦截send方法,如果检测到url需要mock,则返回mock结果*/ const _send = XMLHttpRequest.prototype.send; /*在调用xhr.open的时候保存url,因为在send的时候xhr.responseURL是空的*/ const _open = XMLHttpRequest.prototype.open; // @ts-ignore XMLHttpRequest.prototype.open = function (method, url, async, username, password) { // @ts-ignore this._openData = { method, url, async, username, password }; return _open.apply(this, [method, url, async, username, password]); }; XMLHttpRequest.prototype.send = function (data: any) { // @ts-ignore const responseURL: string = this._openData.url; // console.log('xhr send interceptor -> ', this, `(${responseURL})`, data); /*计算请求url以及url参数,此时url为完整的可能带baseURL的完整路径*/ let { url: _url, param } = ((): { url: string, param: PlainObject | undefined } => { const separatorIndex = responseURL.indexOf('?'); if (separatorIndex === -1) { return { url: responseURL, param: undefined }; } else { return { url: responseURL.slice(0, separatorIndex), param: qs.parse(responseURL.slice(separatorIndex + 1)) }; } })(); // console.log({ _url, param }); _url = pathJoin(_url, '/'); // console.log({ _url, param }); /*计算url相对于baseURL的相对路径,以及标识isMatchBaseURL,是否匹配baseURL*/ const { url, isMatchBaseURL } = ((): { url: string, isMatchBaseURL: boolean } => { if (!baseURL) { return { url: _url, isMatchBaseURL: false }; } else { if (_url == baseURL) { return { url: '/', isMatchBaseURL: true }; } else { if (_url.indexOf(baseURL) === 0) { return { url: _url.slice(baseURL.length), isMatchBaseURL: true, }; } else { return { url: _url, isMatchBaseURL: false, }; } } } })(); // console.log({ url, isMatchBaseURL }); /*判断本次请求是否需要mock*/ const requestInterceptor = requestInterceptors.find(i => {return typeof i.url === "string" ? i.url == url : i.url.test(url);}); if (!!requestInterceptor) { if (typeof data === "string") { try { data = JSON.parse(data); } catch (e) { try { data = qs.parse(data); } catch (e) { data = undefined; } } } Promise.resolve(requestInterceptor.handler({ url, isMatchBaseURL, param, data })).then((respData: any) => { // @ts-ignore // this.readyState = 4; // @ts-ignore // this.responseText = JSON.stringify(respData); // @ts-ignore Object.defineProperty(this, 'responseText', { get(): any { return respData; } }); // @ts-ignore this.onloadend(); }); } else { return _send.apply(this, [data]); } }; function intercept(url: iRequestInterceptor['url'], handler: iRequestInterceptor['handler']): () => void function intercept(config: iRequestInterceptor): () => void function intercept(config: iRequestInterceptor | iRequestInterceptor['url'], handler?: iRequestInterceptor["handler"]) { const _config: iRequestInterceptor = typeof config === "string" || config instanceof RegExp ? { url: config, handler: handler! } : config; requestInterceptors.push(_config); return () => { const index = requestInterceptors.indexOf(_config); index > -1 && requestInterceptors.splice(index, 1); }; }; return { intercept, } } export interface iRequestInterceptor { /*要拦截的url,可以是字符串,也可以是正则表达式*/ url: string | RegExp, /*自定义处理请求并且返回请求结果,支持异步*/ handler: (requestConfig: { url: string, isMatchBaseURL: boolean, param: PlainObject | undefined, data: PlainObject | undefined }) => PlainObject | Promise } export default createRequestInterceptor;