zzzz
2024-04-21 3f3e2d5977787b0c6e09cd5cba7b41e5fb7d3fd0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import axios from "axios"; // 引入axios
//import QS from 'qs'; // 引入qs模块,用来序列化post类型的数据,后面会提到
 
import { Toast, Dialog } from "vant";
import store from "@/store/index";
import i18n from "@/i18n";
import router from "@/router/router";
import { signatureGenerate } from "@/utils/signatureUtil";
import urlKyc from "./urlKyc";
class AxiosRequest {
  /**
   * @description Class AxiosRequest constructor.
   * @param {String} baseUrl Request base url.
   * @param {Object} headers Request headers config.
   * @param {Boolean} isLoading Request loading switch.
   */
  constructor(baseUrl, headers, isLoading) {
    this.baseUrl = baseUrl;
    this.headers = headers;
    this.isLoading = isLoading;
    this.queue = {};
  }
 
  /**
   * @description Get inside config.
   * @returns Inside config.
   */
  getInsideConfig() {
    const config = {
      // alert: Axios default base url param is "baseURL" not is "baseUrl" !
      baseURL: this.baseUrl,
      headers: this.headers,
      timeout: 10000,
    };
    return config;
  }
 
  /**
   * @description Destroy completed request.
   * @param {String} url The completed request.
   */
  destroy(url) {
    delete this.queue[url];
    if (!Object.keys(this.queue).length) {
      // Present request complete.
      // Remove request loading.
      if (this.isLoading) {
        Toast.clear();
      }
    }
  }
 
  /**
   * @description The axios intercept.
   * @param {Function} instance Create axios get instance.
   * @param {String} url Request url.
   */
  interceptors(instance, url) {
    // Request intercept.
    instance.interceptors.request.use(
      (config) => {
        const arr = urlKyc.filter((item) => item === url);
        if (arr.length !== 0 && store.state.user.kyc !== 2) {
          return Toast.fail(i18n.t("请先实名认证!"));
        }
        var token = store.state.user.userInfo.token;
        if (token) {
          if (!config.params) {
            config.params = {};
          }
          config.params.token = token;
          // console.log(config)
          // const METHOD = config.method.toUpperCase()
          // if (METHOD === 'GET') {
          //   if (!config.params) {
          //     config.params = {}
          //   }
          //   config.params.token = token;
          // } else if(METHOD === 'POST') {
          //   if (!config.data) {
          //     config.data = {}
          //   }
          //   config.data.token = token
          // } else {
          //   // TODO
          // }
        }
        if (!Object.keys(this.queue).length) {
          if (this.isLoading) {
            // Add request loading.
            Toast.loading({
              duration: 0,
              forbidClick: true,
              loadingType: "spinner",
              message: i18n.t("加载中..."),
            });
          }
          this.queue[url] = true;
        }
        // 获取请求头参数
        const { timestamp, signature } = signatureGenerate();
        // 分别将签名、时间戳 至请求头
        if (signature) config.headers["sign"] = signature;
        if (timestamp) config.headers["tissuePaper"] = timestamp;
        return config;
      },
      (error) => {
        if (this.isLoading) {
          Toast.clear();
        }
        return Promise.reject(error);
      }
    );
    // Response intercept.
    instance.interceptors.response.use(
      (result) => {
        this.destroy(url);
        if (result.data.code == 0 || result.data.code == 200) {
          return result.data;
        } else if (result.data.code == 401) {
          Dialog.confirm({
            confirmButtonText: i18n.t("确定"),
            cancelButtonText: i18n.t("取消"),
            title: i18n.t("提示"),
            message: i18n.t("未实名认证,是否认证?"),
            beforeClose: (action, done) => {
              if (action === "confirm") {
                done();
                router.push({
                  path: "/authentication",
                });
              } else {
                done();
              }
            },
          });
          return result.data;
        } else if (result.data.code == 403) {
          router.replace({
            path: "/login",
            query: {
              redirect: router.currentRoute.fullPath,
            },
          });
          store.commit("user/SET_OUT");
        } else {
          if (result.data.msg != undefined) {
            Toast(i18n.t(result.data.msg));
          }
          return Promise.reject(result.data);
        }
      },
      (error) => {
        if (this.isLoading) {
          Toast.clear();
        }
        if (error.code == "ERR_NETWORK") {
          Toast({ message: "ERR_NETWORK", type: "fail", duration: 1000 });
        } else if (error.code == "ECONNABORTED") {
          //Toast({ message: 'Network Timeout', type: 'fail', duration: 2000 })
          return Promise.reject(error);
        }
        // if (error.message.includes("timeout")) {
        //   Toast.fail(i18n.t("网络超时!"));
        // }
        return Promise.reject(error);
      }
    );
  }
 
  /**
   * @description Axios request function.
   * @param {Object} options Axios request options.
   * @returns Create axios get instance.
   */
  request(options) {
    const instance = axios.create();
    options = Object.assign(this.getInsideConfig(), options);
    this.interceptors(instance, options.url);
    return instance(options);
  }
}
 
export default AxiosRequest;