-
Notifications
You must be signed in to change notification settings - Fork 19
/
wxhttpclient.ts
371 lines (333 loc) · 9.91 KB
/
wxhttpclient.ts
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import * as utils from "../util"
import {wxConsts} from "./wxconsts"
import {wxSession} from "./wxsession"
import {WxResponseType, WxTaskType, WxTaskPool, WxTask, WxLoginTask, WxUserInfoTask, WxRequestTask} from "./wxhttptask"
import { pop_mgr } from "../ui/pop_mgr"
import { wxTip } from "./wxtips"
interface RequestHandler
{
cb:utils.handler;
ctx:cc.Component;
}
interface RequestParams
{
data?:any;
header?:object;
method?:string;
dataType?:string;
responseType?:string;
}
const buildAuthHeader = () => {
const header = {};
const session = wxSession.get();
if(session)
{
header[wxConsts.WX_HEADER_SKEY] = session;
}
return header;
}
const buildRequestHeader = () => {
const header = {};
header[wxConsts.CONTENT_TYPE] = "application/x-www-form-urlencoded";
return header;
}
export const RequestAction = {
Login:"login",
User:"user",
Pass:"pass",
Share:"share",
Hint:"hint",
Friend:"friend",
Rank:"rank",
GetGift:"getgift",
};
const enum ResponseCode{
ECodeSuccess = 0, // 成功
ECodeError = 1, // 通用错误
ECodeServerError = 2, // 服务器内部数据错误
ECodeNotLogin = 10, // 未登录
ECodeWrongParam = 11, // 错误的参数
ECodeNoEnoughMoney = 12, // 钱不够
ECodeShareSameGroup = 13, //分享到相同的群
}
class WxHttpClient
{
private serverURL:string;
private session:number;
private errorHandler:utils.handler;
private requestHandlers:Map<string, RequestHandler[]>;
private ctxRequests:Map<cc.Component, string[]>;
private taskPool:WxTaskPool;
private taskQueue:WxTask[];//todo, use real queue
constructor()
{
this.session = 0;
this.requestHandlers = new Map();
this.ctxRequests = new Map();
this.taskPool = new WxTaskPool();
this.taskQueue = [];
this.errorHandler = utils.gen_handler(this.defaultErrorHandler, this);
}
private createTask(taskType:WxTaskType)
{
let task = this.getFromPool(taskType);
if(task)
{
return task;
}
if(taskType == WxTaskType.Login)
{
return new WxLoginTask(taskType);
}
else if(taskType == WxTaskType.UserInfo)
{
return new WxUserInfoTask(taskType);
}
else if(taskType == WxTaskType.Request)
{
return new WxRequestTask(taskType);
}
else
{
console.log("unknown task type");
return null;
}
}
private getFromPool(taskType:WxTaskType)
{
return this.taskPool.get(taskType);
}
private putToPool(taskType:WxTaskType, task:WxTask)
{
this.taskPool.put(taskType, task);
}
setServerURL(url:string)
{
this.serverURL = url;
}
login()
{
//wx.login
const task:WxTask = this.createTask(WxTaskType.Login);
task.init(
{},
utils.gen_handler(this.handleWxLogin, this),
);
task.exec();
}
private handleWxLogin(taskType:WxTaskType, task:WxTask, responseType:WxResponseType, resp)
{
this.putToPool(taskType, task);
if(responseType === WxResponseType.Fail)
{
console.log("WxLoginTask fail", resp);
return;
}
if(responseType === WxResponseType.Complete)
{
console.log("WxLoginTask complete", resp);
return;
}
console.log("WxLoginTask success", resp);
//wx.login->wx.getUserInfo
task = this.createTask(WxTaskType.UserInfo);
task.init(
{
withCredentials:true,
lang:"zh_CN",
},
utils.gen_handler(this.handleWxGetUserInfo, this),
resp.code,
);
task.exec();
}
private handleWxGetUserInfo(taskType:WxTaskType, task:WxTask, responseType:WxResponseType, resp, code:string)
{
this.putToPool(taskType, task);
if(responseType === WxResponseType.Fail)
{
console.log("WxUserInfoTask fail", resp);
return;
}
if(responseType === WxResponseType.Complete)
{
console.log("WxUserInfoTask complete", resp);
return;
}
console.log("WxUserInfoTask success", resp);
//wx.login->wx.getUserInfo->wx.request->应用程序登录
this.request(RequestAction.Login, {
header:{
[wxConsts.WX_HEADER_CODE]:code,
[wxConsts.WX_HEADER_ENCRYPTED_DATA]:resp.encryptedData,
[wxConsts.WX_HEADER_IV]:resp.iv,
}
}, resp.userInfo);
}
request(action:string, params?:RequestParams, ...reqData)
{
if(!this.serverURL)
{
console.log("should call setServerURL before");
return;
}
//需要登录才能调用其它接口
if(action !== RequestAction.Login && !wxSession.get())
{
//todo 跳转到登录页
return;
}
const task:WxTask = this.createTask(WxTaskType.Request);
task.init(
{
url:`${this.serverURL}/${action}`,
data:(params && params.data) || {},
header:utils.extend({}, (params && params.header) || {}, buildAuthHeader(), buildRequestHeader()),
method:(params && params.method) || "POST",
dataType:(params && params.dataType) || "json",
responseType:(params && params.responseType) || "text",
},
utils.gen_handler(this.handleResponse, this),
action,
...reqData,
);
//避免超过最大并发数量
// if(this.session > WxConsts.MaxRequests)
// {
// this.taskQueue = this.taskQueue || [];
// this.taskQueue.push(task);
// TimerMgr.getInst().once(1/30, utils.gen_handler(() => {
// const req2 = this.taskQueue.shift()
// }, this));
// }
// else
// {
task.exec();
this.session++;
// }
}
private handleResponse(taskType:WxTaskType, task:WxTask, responseType:WxResponseType, resp, action:string, ...reqData)
{
//回收入池
this.session--;
this.putToPool(taskType, task);
if(responseType === WxResponseType.Fail)
{
console.log(`WxTaskType${taskType} ${action} fail`, resp);
return;
}
if(responseType === WxResponseType.Complete)
{
console.log(`WxTaskType${taskType} ${action} complete`, resp);
return;
}
console.log(`WxTaskType${taskType} ${action} success`, resp);
//msg是开发者服务器返回的数据, 结构{code, errmsg, data}
const msg = resp.data;
const isOK = msg.code === 0;
if(!isOK)
{
this.errorHandler.exec(msg.code, msg.errmsg);
}
//执行请求监听函数
const handlers = this.requestHandlers.get(action);
if(!handlers)
{
return;
}
handlers.forEach(h => {
if(!cc.isValid(h.ctx))
{
return;
}
h.cb.exec(isOK, msg.data, ...reqData);
});
}
registerHandler(action:string, cb:utils.handler, ctx:cc.Component)
{
//request -> handler
let handlers = this.requestHandlers.get(action);
if(!handlers)
{
handlers = [];
this.requestHandlers.set(action, handlers);
}
handlers.push({cb, ctx});
//context -> requests
let requests = this.ctxRequests.get(ctx);
if(!requests)
{
requests = [];
this.ctxRequests.set(ctx, requests);
}
requests.push(action);
}
unregisterHandler(action:string, cb:utils.handler, ctx:cc.Component)
{
//remove from requestHandlers
const handlers = this.requestHandlers.get(action);
if(handlers && handlers.length)
{
const index = handlers.findIndex(h => h.cb == cb && h.ctx == ctx);
if(index !== -1)
{
handlers.splice(index, 1);
}
}
//remove from ctxRequests
const requests = this.ctxRequests.get(ctx);
if(requests && requests.length)
{
const index = requests.findIndex(r => r === action);
if(index !== -1)
{
requests.splice(index, 1);
}
}
}
unregisterCtxHandler(ctx:cc.Component)
{
const requests = this.ctxRequests.get(ctx);
if(!requests)
{
return;
}
requests.forEach(r => {
const handlers = this.requestHandlers.get(r);
if(!handlers)
{
return;
}
for(let i = handlers.length - 1; i >= 0; i--)
{
if(handlers[i].ctx !== ctx)
{
continue;
}
handlers.splice(i, 1);
}
});
requests.length = 0;
}
registerErrorHandler(handler:utils.handler)
{
this.errorHandler = handler;
}
private defaultErrorHandler(code:ResponseCode, errmsg:string)
{
console.log(`请求响应失败, code=${code}`, errmsg);
//需要重新登录, 跳到登录页
if(code == ResponseCode.ECodeNotLogin)
{
wxSession.clear();
//跳到登录页
wxTip.showToast("本次会话过期,请重新登录");
pop_mgr.get_inst().clear();
}
else if(code == ResponseCode.ECodeShareSameGroup)
{
wxTip.showToast("试试分享到不同的群吧");
}
}
}
export const wxHttpClient:WxHttpClient = new WxHttpClient();