index.js
2.96 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
module.exports = function() {
const webSocketServer = require('ws').Server;
var clients = [];
const objWs = {};
objWs.wsServer = new webSocketServer({
port: config.port
});
function noop() {}
function heartbeat() {
this.isAlive = true;
}
objWs.wsServer.on('connection', function connection(ws) {
console.log('open socket server');
ws.isAlive = true;
ws.on('pong', heartbeat);
ws.on('message', function incoming(message) {
message = JSON.parse(message.toString('utf8'));
switch (message.action) {
case 'gln':
clients.push({ws: ws, gln: message.gln});
break;
default:
// console.log(message.action);
}
});
});
const interval = setInterval(function ping() {
objWs.wsServer.clients.forEach(function each(ws) {
if (ws.isAlive === false) return ws.terminate();
ws.isAlive = false;
ws.ping(noop);
});
}, 10000);
objWs.getEntidad = function(gln, tableName, where, queryString) {
return new Promise(function(resolve, reject) {
var client = clients.filter(function(client) {
return client.gln == gln
})[0];
if (!client) {
reject('No se encuentra el webSocket client');
}
var idSolicitud = Math.round(Math.random() * 1000);
var enviar = {
action: 'getEntity',
idSolicitud: idSolicitud
};
if (queryString) {
enviar.queryString = queryString;
} else {
enviar.tableName = tableName;
enviar.where = where || {};
}
client.ws.send(JSON.stringify(enviar));
client.ws.on('message', function(message) {
message = JSON.parse(message);
if (idSolicitud == message.idSolicitud) {
resolve(message.data);
}
});
});
}
objWs.getClientGln = function(gln) {
return clients.filter(function(client) {
return client.gln = gln;
});
}
objWs.guardarComprobante = function (cuerpo, gln) {
return new Promise((resolve, reject) => {
var client = clients.filter(function(client) {
return client.gln == gln
})[0];
if (!client) {
reject('No se encuentra el webSocket client');
console.log('No se encuentra el webSocket client');
return;
}
var idSolicitud = Math.round(Math.random() * 1000);
var enviar = {
action: 'comprobante',
req: cuerpo,
idSolicitud: idSolicitud
};
console.log(`enviando comprobante a cliente`)
console.log(cuerpo.cabecera);
client.ws.send(JSON.stringify(enviar));
client.ws.on('message', function(message) {
message = JSON.parse(message);
console.log(message);
if (idSolicitud == message.idSolicitud) {
if (message.ok) {
console.log('resuelve comprobante en estación')
resolve();
} else {
reject();
}
}
});
});
}
return objWs;
}