-
Notifications
You must be signed in to change notification settings - Fork 0
/
requestToBridge.js
119 lines (100 loc) · 2.96 KB
/
requestToBridge.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
109
110
111
112
113
114
115
116
117
118
119
function RequestToBridge(request, queryString){
this.request = request;
this.queryString = queryString;
this.logger = require('nogg').logger('requestToBridge');
};
RequestToBridge.prototype = {
setIo: function(io){
this.io = io;
},
/**
* @param socket
* @param eventName
* @param eventParameters
* @param cb
*/
execute: function(socket, eventName, eventParameters, cb){
if(typeof eventParameters != "object"){
eventParameters = {};
}
var body = this.getBody(socket, [{
name: eventName,
parameters: eventParameters
}]);
var cbs = {};
if(typeof cb == "function"){
cbs[eventName] = cb;
}
this.logger.debug(eventName);
this.send(socket.handshake.bridgeUri, body, cbs);
},
/**
* @param socket
* @param events
* @param cbs
*/
executeMultiple: function(socket, events, cbs){
var body = this.getBody(socket, events);
this.send(socket.handshake.bridgeUri, body, cbs);
},
/**
* @param uri
* @param body
* @param cbs
*/
send: function(uri, body, cbs){
var self = this;
this.request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
uri: uri,
body: body
}, function(err, response, body){
self.logger.debug(body);
try{
var json = JSON.parse(body);
}catch(e){
var json = null;
}
if(!json || typeof json.events != "object"){
return;
}
for(var eventName in json.events){
if(cbs[eventName] && typeof cbs[eventName] == "function"){
cbs[eventName](null, json.events[eventName]);
}
}
return;
});
},
/**
* @param socket
* @param events
* @param isDisconnecting
* @return {*}
*/
getBody: function(socket, events, isDisconnecting){
if(typeof isDisconnecting == undefined){
isDisconnecting = false;
}
var users = {};
this.io.of('/'+socket.handshake.apiName).clients().forEach(function(roomSocket){
if(isDisconnecting == true && roomSocket.id == socket.id){
return;
}
var identification = roomSocket.handshake.identification;
if(!users[identification]){
users[identification] = [];
}
users[identification].push(roomSocket.id);
});
return this.queryString.stringify({
socketId: socket.id,
identification: socket.handshake.identification,
users: JSON.stringify(users),
events: JSON.stringify(events)
});
}
};
module.exports = function(request, queryString){
return new RequestToBridge(request, queryString);
}