This repository was archived by the owner on Oct 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.js
108 lines (87 loc) · 2.74 KB
/
request.js
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
import getUrl from './libs/getUrl';
import Promisify from './libs/promisify';
import report from './libs/report';
import User from './libs/user';
import doLogin from './libs/doLogin';
import requestTasks from './libs/requestTasks';
const regeneratorRuntime = require('./libs/regenerator-runtime/runtime-module');
const DEFAULT_CONFIG = {
showLoading: true,
needAuthLogin: true,
autoCatch: true
};
//promisify wx api
const wxlogin = Promisify(wx.login);
const requestPromise = Promisify(wx.request);
/**
* 逻辑判断登录函数
*/
const request = async (url, data = {}, oriConfig = {}) => {
oriConfig = { ...DEFAULT_CONFIG, ...oriConfig };
const args = { url: getUrl(url), data, oriConfig };
const user = User.get();
if (oriConfig.needAuthLogin && !user.id) {
await doLogin();
}
if (oriConfig.needWxCode) {
const { code } = await wxlogin();
args.data.code = code;
}
return doReqWithConfig(args);
};
//业务上的请求逻辑代码处理和封装
const doReqWithConfig = async args => {
let requestTaskKey;
const { url, data, oriConfig } = args;
const { showLoading, contentType, autoCatch, loadingTxt, ...config } = oriConfig;
if (showLoading) {
loadingTxt ? wx.showLoading({title:loginTxt}) : wx.showLoading();
}
const requestTaskPromisify = requestPromise({
url,
data,
method: config.method || 'POST',
header: {
Authorization: User.get().Authorization,
'Content-Type': contentType || 'application/x-www-form-urlencoded'
}
})
.then(async result => {
console.log('result', result);
const { statusCode, data: wrapData, errMsg } = result;
const { code, data, msg, message } = wrapData || {};
if (statusCode == 200 && code == 200) {
return data;
}
//reLogin
if ((code >= 10000 && code <= 10010)) {
wx.showLoading({title:'重新登陆...'});
await doLogin();
return doReqWithConfig(args);
}
//other code
return Promise.reject({
code: code || statusCode,
errMsg: msg || message || errMsg
});
})
.catch(error => {
console.log(error, 'error');
let { errMsg = '', code } = error;
//code=502 ,essMsg 可能为ok
if (~errMsg.indexOf('request:ok')) {
errMsg = '';
}
if (~errMsg.indexOf('interrupted') || ~errMsg.indexOf('abort')) return;
report({ url, msg: errMsg, data: args, isShow: autoCatch, code });
})
.finally(e => {
//complete delete requestTast
showLoading && wx.hideToast();
requestTasks.remove(requestTaskKey);
});
//方便使用requestTask.abort()A
requestTaskKey = requestTasks.add(url, requestTaskPromisify.origin);
return requestTaskPromisify;
};
module.exports = request;