request.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { WxLoginUsingGetResponse } from "@/apis/userApi";
  2. import APPConfig from "@/config";
  3. import Taro from "@tarojs/taro";
  4. import qs from "qs";
  5. import ModalUtil from "./modalUtil";
  6. import StorageUtil, { EStorage } from "./storageUtil";
  7. interface IRequestBaseResult<T> {
  8. code?: 0;
  9. data: T;
  10. msg: string;
  11. }
  12. interface IRequestOptions {
  13. tips?: string | true;
  14. success?: string | true;
  15. errorTips?: string | true;
  16. loading?: string | true;
  17. contentType?: "json" | "urlencoded" | "formData";
  18. data?: Record<string, any>,
  19. params?: Record<string, any>,
  20. }
  21. export interface AxiosRequestConfigFunc<B, P> extends Omit<IRequestOptions, "data" | "params"> {
  22. data?: B,
  23. params?: P
  24. }
  25. export default class RequestUtil<T> {
  26. promise: Promise<Taro.request.SuccessCallbackResult<IRequestBaseResult<T>>>;
  27. public constructor(url: string, method: "POST" | "GET" | "PUT" | "DELETE", options: IRequestOptions) {
  28. this.promise = this.runRequest(url, method, options);
  29. }
  30. public runRequest(url: string, method: "POST" | "GET" | "PUT" | "DELETE", options: IRequestOptions) {
  31. options.loading && Taro.showLoading();
  32. return new Promise<Taro.request.SuccessCallbackResult<IRequestBaseResult<T>>>((resolve, rej) => {
  33. if (options.params) {
  34. url += "?" + qs.stringify(options.params);
  35. }
  36. url = APPConfig.HOST + url;
  37. let userInfo = StorageUtil.get<WxLoginUsingGetResponse>(EStorage.userInfo);
  38. Taro.request({
  39. url,
  40. method,
  41. header: { userId: userInfo?.userId, "appId": APPConfig.APPID, runPlatform: 1, token: userInfo?.token },
  42. data: options.data,
  43. fail: () => {
  44. options.loading && Taro.hideLoading();
  45. rej();
  46. },
  47. success: (res) => {
  48. options.loading && Taro.hideLoading();
  49. let _success = this.checkSuccessSync(res);
  50. if (_success && options.success) {
  51. ModalUtil.toast(typeof (options.success) === "string" ? options.success : res.data.msg);
  52. }
  53. else {
  54. options.errorTips && ModalUtil.toast(res.data.msg);
  55. }
  56. resolve(res);
  57. },
  58. })
  59. });
  60. }
  61. private checkSuccessSync(data: Taro.request.SuccessCallbackResult<IRequestBaseResult<T>>) {
  62. return data.statusCode >= 200 && data.statusCode < 300 && data.data.code === 0;
  63. }
  64. /**是否正确 */
  65. public async checkSuccess() {
  66. return this.promise.then(this.checkSuccessSync)
  67. }
  68. public async toData() {
  69. return this.promise
  70. .then((p) => {
  71. if (this.checkSuccessSync(p)) {
  72. return p.data.data;
  73. }
  74. return null;
  75. })
  76. }
  77. }