traintimesPWA/server/lib/wshandlerv3.js
Martin Donnelly 1e03d1697a wip
2020-08-16 20:05:28 +01:00

69 lines
1.5 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 PubSubManager = require('./pubsub');
const logger = require('log4js').getLogger('wshandlerv3');
logger.level = 'debug';
const pubSubManager = new PubSubManager();
module.exports = function(events, wsServer) {
'use strict';
logger.debug('>> new WS', wsServer);
wsServer.on('connection', (ws, req) => {
console.log(`Connection request from: ${req.connection.remoteAddress}`);
ws.on('message', (data) => {
console.log(`data: ${ data}`);
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.');
});
});
const sendTweetHandler = (id, obj) => {
logger.debug('sendTweetHandler', id, obj);
pubSubManager.publishTwitter(id, obj);
/*
try {
ws.send(JSON.stringify(obj));
}
catch (err) {
logger.error(err);
logger.warn('Offending object: ', obj);
}
*/
};
events.on('sendTweet', sendTweetHandler);
return module;
};