request.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import Taro from "@tarojs/taro";
  2. import qs from "qs";
  3. import ModalUtil from "./modalUtil";
  4. interface IRequestBaseResult<T> {
  5. code?: 0;
  6. data: T;
  7. msg: string;
  8. }
  9. interface IRequestOptions {
  10. tips?: string | true;
  11. success?: string | true;
  12. errorTips?: string | true;
  13. loading?: string | true;
  14. contentType?: "json" | "urlencoded" | "formData";
  15. data?: Record<string, any>,
  16. params?: Record<string, any>,
  17. }
  18. export interface AxiosRequestConfigFunc<B, P> extends Omit<IRequestOptions, "data" | "params"> {
  19. data?: B,
  20. params?: P
  21. }
  22. export default class RequestUtil<T> {
  23. promise: Promise<Taro.request.SuccessCallbackResult<IRequestBaseResult<T>>>;
  24. public constructor(url: string, method: "POST" | "GET" | "PUT" | "DELETE", options: IRequestOptions) {
  25. this.promise = this.runRequest(url, method, options);
  26. }
  27. public runRequest(url: string, method: "POST" | "GET" | "PUT" | "DELETE", options: IRequestOptions) {
  28. return new Promise<Taro.request.SuccessCallbackResult<IRequestBaseResult<T>>>((resolve, rej) => {
  29. if (options.params) {
  30. url += "?" + qs.stringify(options.params);
  31. }
  32. Taro.request({
  33. url,
  34. method,
  35. data: options.data,
  36. fail: () => {
  37. options.loading && Taro.hideLoading();
  38. rej();
  39. },
  40. success: (res) => {
  41. // if (typeof res.data === "string") {
  42. // try {
  43. // res.data = JSON.parse(res.data);
  44. // } catch (error) {
  45. // }
  46. // }
  47. options.loading && Taro.hideLoading();
  48. let _success = this.checkSuccessSync(res);
  49. if (_success) {
  50. ModalUtil.toast(typeof (options.success) === "string" ? options.success : res.data.msg);
  51. }
  52. else {
  53. ModalUtil.toast(res.data.msg);
  54. }
  55. // else if (res.data.code !== 0 && (options.tips || options.errorTips)) {
  56. // }
  57. // else if (res.data.code === 10001) {
  58. // // ModalUtil.toast("登录失效");
  59. // // MemberHelper.clearMemberInfo();
  60. // // Taro.reLaunch({
  61. // // url: "/pages/user/userLogin/index"
  62. // // })
  63. // }
  64. resolve(res);
  65. },
  66. })
  67. });
  68. }
  69. private checkSuccessSync(data: Taro.request.SuccessCallbackResult<IRequestBaseResult<T>>) {
  70. return data.statusCode >= 200 && data.statusCode < 300 && data.data.code === 0;
  71. }
  72. /**是否正确 */
  73. public async checkSuccess() {
  74. return this.promise.then(this.checkSuccessSync)
  75. }
  76. public async toData() {
  77. return this.promise
  78. .then((p) => {
  79. if (this.checkSuccessSync(p)) {
  80. return p.data.data;
  81. }
  82. return null;
  83. })
  84. }
  85. }