all files / src/ pubsub.js

37.5% Statements 9/24
16.67% Branches 1/6
33.33% Functions 1/3
37.5% Lines 9/24
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                                                                             
 
'use strict';
 
var nconf = require('nconf'),
	util = require('util'),
	winston = require('winston'),
	EventEmitter = require('events').EventEmitter;
 
var channelName;
 
var PubSub = function() {
	var self = this;
	Iif (nconf.get('redis')) {
		var redis = require('./database/redis');
		var subClient = redis.connect();
		this.pubClient = redis.connect();
 
		channelName = 'db:' + nconf.get('redis:database') + 'pubsub_channel';
		subClient.subscribe(channelName);
 
		subClient.on('message', function(channel, message) {
			if (channel !== channelName) {
				return;
			}
 
			try {
				var msg = JSON.parse(message);
				self.emit(msg.event, msg.data);
			} catch(err) {
				winston.error(err.stack);
			}
		});
	}
};
 
util.inherits(PubSub, EventEmitter);
 
PubSub.prototype.publish = function(event, data) {
	if (this.pubClient) {
		this.pubClient.publish(channelName, JSON.stringify({event: event, data: data}));
	} else {
		this.emit(event, data);
	}
};
 
var pubsub = new PubSub();
 
module.exports = pubsub;