-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpacket-handler.js
51 lines (45 loc) · 1.26 KB
/
packet-handler.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
const userSocket = require('./ws-handler');
function PacketHandler(fn) {
this.middlewares = [];
}
PacketHandler.prototype.use = function use(fn) {
this.middlewares.push(fn);
}
PacketHandler.prototype.process = function process(packet, ws) {
var middlewares = this.middlewares.map(function(use){
return use;
});
try {
packet = JSON.parse(packet);
packet.reply = { act: packet.act, packetId: packet.packetId || 0 };
} catch(parseError) {
packet = { reply: {
error: true,
errorDesc: 'json parse error'
}};
}
function done() {
if (packet && packet.reply) {
ws.send(JSON.stringify(packet.reply));
}
/* save session associated with a user */
if (packet.__id
&& userSocket.get(packet.__id) !== ws) {
userSocket.set(packet.__id, ws);
}
middlewares = [];
}
function next() {
if (middlewares.length) {
var fn = middlewares.shift();
fn.apply(null, [packet, next.bind(null), done.bind(null)]);
} else {
done();
}
}
next();
}
PacketHandler.prototype.destroy = function destroy() {
this.middleware = null;
}
module.exports = PacketHandler;