import Taro from "@tarojs/taro"; import qs from "qs"; import ModalUtil from "./modalUtil"; interface IRequestBaseResult { code?: 0; data: T; msg: string; } interface IRequestOptions { tips?: string | true; success?: string | true; errorTips?: string | true; loading?: string | true; contentType?: "json" | "urlencoded" | "formData"; data?: Record, params?: Record, } export interface AxiosRequestConfigFunc extends Omit { data?: B, params?: P } export default class RequestUtil { promise: Promise>>; public constructor(url: string, method: "POST" | "GET" | "PUT" | "DELETE", options: IRequestOptions) { this.promise = this.runRequest(url, method, options); } public runRequest(url: string, method: "POST" | "GET" | "PUT" | "DELETE", options: IRequestOptions) { return new Promise>>((resolve, rej) => { if (options.params) { url += "?" + qs.stringify(options.params); } Taro.request({ url, method, data: options.data, fail: () => { options.loading && Taro.hideLoading(); rej(); }, success: (res) => { // if (typeof res.data === "string") { // try { // res.data = JSON.parse(res.data); // } catch (error) { // } // } options.loading && Taro.hideLoading(); let _success = this.checkSuccessSync(res); if (_success) { ModalUtil.toast(typeof (options.success) === "string" ? options.success : res.data.msg); } else { ModalUtil.toast(res.data.msg); } // else if (res.data.code !== 0 && (options.tips || options.errorTips)) { // } // else if (res.data.code === 10001) { // // ModalUtil.toast("登录失效"); // // MemberHelper.clearMemberInfo(); // // Taro.reLaunch({ // // url: "/pages/user/userLogin/index" // // }) // } resolve(res); }, }) }); } private checkSuccessSync(data: Taro.request.SuccessCallbackResult>) { return data.statusCode >= 200 && data.statusCode < 300 && data.data.code === 0; } /**是否正确 */ public async checkSuccess() { return this.promise.then(this.checkSuccessSync) } public async toData() { return this.promise .then((p) => { if (this.checkSuccessSync(p)) { return p.data.data; } return null; }) } }