refactor websockets app

This commit is contained in:
Ivan Socolsky 2015-05-06 16:26:43 -03:00
parent 86525ce6ef
commit bfaf7ff5c4
2 changed files with 14 additions and 15 deletions

4
bws.js
View File

@ -37,7 +37,7 @@ var start = function(cb) {
if (err) return cb(err);
var server = config.https ? serverModule.createServer(serverOpts, app) :
serverModule.Server(app);
WsApp.start(server, config);
new WsApp().start(server, config);
return server;
});
});
@ -47,7 +47,7 @@ var start = function(cb) {
if (err) return cb(err);
server = config.https ? serverModule.createServer(serverOpts, app) :
serverModule.Server(app);
WsApp.start(server, config);
new WsApp().start(server, config);
return cb(null, server);
});
};

View File

@ -9,44 +9,43 @@ var Uuid = require('uuid');
var WalletService = require('./server');
var MessageBroker = require('./messagebroker');
var BlockchainMonitor = require('./blockchainmonitor');
log.level = 'debug';
var io, messageBroker, blockchainMonitor;
var WsApp = function() {};
WsApp._unauthorized = function(socket) {
WsApp.prototype._unauthorized = function(socket) {
socket.emit('unauthorized');
socket.disconnect();
};
WsApp._handleNotification = function(notification) {
io.to(notification.walletId).emit('notification', notification);
WsApp.prototype._handleNotification = function(notification) {
this.io.to(notification.walletId).emit('notification', notification);
};
WsApp.start = function(server, opts, cb) {
WsApp.prototype.start = function(server, opts, cb) {
opts = opts || {};
$.checkState(opts.messageBrokerOpts);
io = require('socket.io')(server);
var self = this;
this.io = require('socket.io')(server);
async.series([
function(done) {
messageBroker = new MessageBroker(opts.messageBrokerOpts);
messageBroker.onMessage(WsApp._handleNotification);
self.messageBroker = new MessageBroker(opts.messageBrokerOpts);
self.messageBroker.onMessage(_.bind(self._handleNotification, self));
done();
},
function(done) {
io.on('connection', function(socket) {
self.io.on('connection', function(socket) {
socket.nonce = Uuid.v4();
socket.on('authorize', function(data) {
if (data.message != socket.nonce) return WsApp._unauthorized(socket);
if (data.message != socket.nonce) return self._unauthorized(socket);
WalletService.getInstanceWithAuth(data, function(err, service) {
if (err) return WsApp._unauthorized(socket);
if (err) return self._unauthorized(socket);
socket.join(service.walletId);
socket.emit('authorized');