import { Toast } from "antd-mobile"; import axios, { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from "axios"; import type { AxiosOptions } from "./type"; type Result = { code: number; msg: string; data: T; }; interface CustomRequestConfig { toast?: boolean; } export default class Request { private axiosInstance: AxiosInstance; private readonly options: AxiosOptions; constructor(options: AxiosOptions) { this.axiosInstance = axios.create(options); this.options = options; this.setupInterceptors(); } setupInterceptors() { // 定义拦截器 const { options: { transform }, axiosInstance, } = this; // 如果没有自定义拦截器则返回 if (!transform) { return; } // 解包拦截器 const { requestInterceptor, requestInterceptorCatch, responseInterceptor, responseInterceptorCatch, } = transform; /** * @description 全局请求拦截 */ axiosInstance.interceptors.request.use( async (config: InternalAxiosRequestConfig & CustomRequestConfig) => { if (requestInterceptor) { config = requestInterceptor(config); // header请求头添加token let globalStore = window.localStorage.getItem("globalStore") || ""; if (globalStore) { let userInfo = JSON.parse(globalStore); config.headers["Token"] = userInfo?.state?.token; } if (config && config?.toast) { Toast.show({ icon: "loading", content: "请求中...", duration: 0, maskClickable: false, }); } } return config; }, (error) => { if (requestInterceptorCatch) { requestInterceptorCatch(error); } } ); /** * @description 全局响应拦截 */ axiosInstance.interceptors.response.use( (res) => { Toast.clear(); if (responseInterceptor) { res = responseInterceptor(res); } return res; }, (error) => { if (responseInterceptorCatch) { responseInterceptorCatch(error); } Toast.clear(); } ); } /** * @description 单个实列请求 */ request(config: AxiosOptions): Promise> { return new Promise((resolve, reject) => { this.axiosInstance .request>(config) .then((res) => { const { transform } = config; if (transform && transform.responseInterceptor) { res = transform.responseInterceptor(res); } resolve(res.data); }) .catch((error) => { reject(error); }); }); } get(config: AxiosOptions): Promise> { return this.request({ ...config, method: "get" }); } post(config: AxiosOptions): Promise> { return this.request({ ...config, method: "post" }); } put(config: AxiosOptions): Promise> { return this.request({ ...config, method: "put" }); } delete(config: AxiosOptions): Promise> { return this.request({ ...config, method: "delete" }); } }