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(message.code); } } }); }); } return objWs; }