123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- import Taro from "@tarojs/taro";
- import qs from "qs";
- import ModalUtil from "./modalUtil";
- interface IRequestBaseResult<T> {
- 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<string, any>,
- params?: Record<string, any>,
- }
- export interface AxiosRequestConfigFunc<B, P> extends Omit<IRequestOptions, "data" | "params"> {
- data?: B,
- params?: P
- }
- export default class RequestUtil<T> {
- promise: Promise<Taro.request.SuccessCallbackResult<IRequestBaseResult<T>>>;
- 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<Taro.request.SuccessCallbackResult<IRequestBaseResult<T>>>((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<IRequestBaseResult<T>>) {
- 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;
- })
- }
- }
|