traintimesPWA/server/lib/wshandlerv3.js
Martin Donnelly da5d1384c5 * Twitter now cleans db on restart
* Server now handles websockets and sends tweets to websocket

* Added new ecosystem for pm2 to control server/twitter
2020-08-19 11:25:53 +01:00

79 lines
1.7 KiB
JavaScript

/**
*
* User: Martin Donnelly
* Date: 2016-09-07
* Time: 15:33
*
*/
// from
// https://medium.com/unprogrammer/implementing-publisher-subscriber-pattern-using-javascript-nodejs-and-websockets-82036da7e174
const url = require('url');
const cuid = require('cuid');
const PubSubManager = require('./pubsub');
const logger = require('log4js').getLogger('wshandlerv3');
logger.level = 'debug';
const pubSubManager = new PubSubManager();
function noop() {}
function heartbeat() {
this.isAlive = true;
}
module.exports = function(events, wsServer) {
'use strict';
logger.debug('>> new WS', wsServer);
wsServer.on('connection', (ws, req) => {
ws.cuid = cuid();
console.log(`Connection request for ${ws.cuid}`);
ws.isAlive = true;
ws.on('pong', heartbeat);
ws.on('message', (data) => {
console.log(`data: ${ data}`, this);
const json = JSON.parse(data);
const request = json.request;
const message = json.message;
const channel = json.channel;
switch (request) {
case 'PUBLISH':
pubSubManager.publish(ws, channel, message);
break;
case 'SUBSCRIBE':
pubSubManager.subscribe(ws, channel);
break;
}
});
ws.on('close', () => {
console.log('Stopping client connection.', ws.cuid);
pubSubManager.unsubscribe(ws.cuid);
});
});
const interval = setInterval(function ping() {
wsServer.clients.forEach(function each(ws) {
if (ws.isAlive === false) return ws.terminate();
ws.isAlive = false;
ws.ping(noop);
});
}, 30000);
const sendTweetHandler = (id, obj) => {
pubSubManager.publishTwitter(id, obj);
};
events.on('sendTweet', sendTweetHandler);
return module;
};