api.js
8.49 KB
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/**
* Created by goto9 on 2018/7/19.
*/
//接口地址,测试环境请修改以下地址
//const server_host='https://xt04.colorcun.com/?s=';
const api_timeout = 2000; //接口超时时间,默认2s
//引入接口映射关系表
import api from './api.url'
import uri_dc from './uri'
import bot from './rebot'
const server_host = uri_dc.HOST__LINE;
class rpcm {
tasks = {}
check(key) {
let nt = new Date().getTime()
if (this.tasks[key]) {
//console.log('resSetIntervalnt',nt , this.tasks[key].timeout)
if (nt <= this.tasks[key].timeout) {
return true
}
}
return false
}
get(key) {
return new Promise((success, fail) => {
let resSetInterval=setInterval(()=>{
console.log('resSetInterval',key,this.tasks[key])
if(this.tasks[key].type=='success'){
wx.hideLoading();
success(this.tasks[key].res)
clearInterval(resSetInterval)
}
if(this.tasks[key].type=='fail'){
wx.hideLoading();
fail(this.tasks[key].res)
clearInterval(resSetInterval)
}
},500)
})
}
set(key,type='',res=null) {
let nt = new Date().getTime()
this.tasks[key] = {
timeout: nt + 1000
}
if(type){
this.tasks[key]['type']=type
this.tasks[key]['res']=JSON.parse(JSON.stringify(res))
}
}
}
const RMT = new rpcm()
/**
*
* @param act
* @param data
* @param fouce false|true 强制请求服务器,获取最新数据;默认优先使用缓存
* @param header 追加header
* @param silence loading
* @param cachetime 缓存时间
* @param timeout 接口超时
* @returns {Promise}
*/
function rpc(host = '', act, data = {}, fouce = false, header = {}, silence = true, cachetime = 0, timeout = api_timeout, api = {}) {
host = host ? host : server_host;
let param = "";
for (let key in data) {
let val = data[key];
//if (val !== "" && val !== null) {
param += '&' + key + '=' + val
//}
}
let cache_key = act;
if (param) {
cache_key += '?' + param.substr((param.length - 1) * -1);
}
if (fouce == 'clear' || fouce == 'clean') {
return wx.removeStorageSync(cache_key);
}
if (!fouce && cachetime != 0) {//优先使用缓存
let getCache = cache(cache_key);
//console.log('getCache.'+getCache,cache_key);
if (getCache != -99999) {
return new Promise((success, fail) => {
getCache.isCache = true;
console.log(cache_key + '\nuse cache', getCache);
success(getCache);
})
}
}
if (!silence) {
wx.showLoading({
title: '处理中',
mask: true
})
}
if (RMT.check(cache_key) && !api.hasDisabledRMT) return RMT.get(cache_key)
RMT.set(cache_key)
return new Promise(async(success, fail) => {
if(api.msgSecCheck){//数据安全检查
try{
await msgSecCheck(host,data)
}catch (e){
wx.showToast({
title:'内容含有违法违规内容',
icon:'none'
})
return fail({msgSecCheck:true})
}
}
let openid = wx.getStorageSync('customer_openid');
let formids = wx.getStorageSync('formids');
if (formids) {
wx.removeStorage({key: 'formids'});
}
let enter_params = wx.getStorageSync('enter_params');
let operator = ''
if (enter_params) {
operator = JSON.stringify({
uid: enter_params.manager_id,
openid: enter_params.seller_openid,
sid: enter_params.seller_id,
})
}
if (api.openid) {
data[api.openid] = data[api.openid] || openid;
}
let stime = new Date();
wx.request({
url: host + act,
method: 'POST',
data: data,
header: {
...header,
openid: openid,
formids: formids.toString(),
operator: operator,
'content-type': 'application/x-www-form-urlencoded'
},
success: function (res) {
let hs=(new Date() - stime)
console.log('request.api[' + hs + 'ms]==>', host + cache_key + '\nrequest.success', res.data);
// return;
//bot.msg({url: host + cache_key, res: res.data})
if (res.data) {
if (cachetime != 0 && res.data.ret == 200) {
cache(cache_key, res.data, cachetime);//.then().catch();
}
if (res.data.ret !== 200) {
try {
res.data.msg = res.data.msg.replace('非法请求:', '');
} catch (e) {
console.log('res-fail', res, e);
bot.msg({url: host + cache_key, res: res.data})
if (wx.getRealtimeLogManager) {
const logger = wx.getRealtimeLogManager()
logger.error('接口错误', {url: host + cache_key, res: res.data})
}
}
}
} else {
bot.msg({url: host + cache_key, res: res})
if (wx.getRealtimeLogManager) {
const logger = wx.getRealtimeLogManager()
logger.error('接口错误', {url: host + cache_key, res: res})
}
}
success(res.data);
RMT.set(cache_key,'success',res.data)
},
fail: function (res) {
console.log('request.api==>', host + cache_key + '\nrequest.fail', res);
fail(res);
RMT.set(cache_key,'fail',res)
// let query = wx.createSelectorQuery().selectComponent("#network");
// let net=query.exec(function(){
// console.log('back=>',arguments);
// });
//query.show();
//console.log('net',query);
bot.msg({url: host + cache_key, res: res})
if (wx.getRealtimeLogManager) {
const logger = wx.getRealtimeLogManager()
logger.error('调用失败', {url: host + cache_key, res: res})
}
},
complete: function () {
let hs=(new Date() - stime)
if (wx.canIUse('reportPerformance')) {
wx.reportPerformance(1001, hs)
}
wx.hideLoading();
}
})
})
}
function __api() {
let tmpApi = {}
let keys = [];
for (let key in api) {
api[key] = api[key] || {};
keys = key.split('.');
tmpApi[keys[0]] = tmpApi[keys[0]] ? tmpApi[keys[0]] : {};
tmpApi[keys[0]][keys[1]] = tmpApi[keys[0]][keys[1]] ? tmpApi[keys[0]][keys[1]] : {};
tmpApi[keys[0]][keys[1]][keys[2]] = function (data, fouce = false, header) {
//console.log('api[key].host',api[key].host);
return rpc(api[key].host, api[key].alias || key, data, fouce, header,
api[key].silence, api[key].cachetime, api[key].timeout, api[key]);
}
}
for (let xkey in uri_dc) {
let key = uri_dc[xkey].toString();
if (key.indexOf('App.') > -1) {
keys = key.split('.');
try {
if (typeof tmpApi[keys[0]][keys[1]][keys[2]] == 'undefined') {
throw new Error('undefined');
}
} catch (e) {
api[key] = api[key] || {};
tmpApi[keys[0]] = tmpApi[keys[0]] ? tmpApi[keys[0]] : {};
tmpApi[keys[0]][keys[1]] = tmpApi[keys[0]][keys[1]] ? tmpApi[keys[0]][keys[1]] : {};
tmpApi[keys[0]][keys[1]][keys[2]] = function (data, fouce = false, header) {
//console.log('api[key].host',api[key]);
return rpc(api[key].host, api[key].alias || key, data, fouce, header,
api[key].silence, api[key].cachetime, api[key].timeout, api[key]);
}
}
}
}
//console.log(tmpApi[keys[0]]);
return tmpApi[keys[0]];
}
function cache(key, val = -99999, timeout = -1) {
if (val != -99999) {//写入
return new Promise((success, fail) => {
let data = {
data: val,
timeout: timeout == -1 ? -1 : (Date.parse(new Date()) / 1000 + timeout)
}
wx.setStorage({
key: key,
data: data,
success: () => {
success()
},
fail: () => {
fail()
}
});
})
}
let res = wx.getStorageSync(key);
let time = Date.parse(new Date()) / 1000;
if (res && (res.timeout == -1 || res.timeout > time) && res.data) {
return res.data;
} else {
return -99999
}
}
function msgSecCheck(host,params){
let content=JSON.stringify(params);
return new Promise(function(success,fail){
wx.request({
url: host + 'App.Wechat.MsgSecCheck',
method: 'POST',
data: {content:content},
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: res => {
if(res.data.data.errcode==0){
success()
}else{
fail()
}
},
fail: res => {
fail()
},
complete:res=>{
wx.hideLoading();
}
})
})
}
export default __api();