diff --git a/src/pubsub.js b/src/pubsub.js index ee6185be20..1df776cd2f 100644 --- a/src/pubsub.js +++ b/src/pubsub.js @@ -4,6 +4,8 @@ var EventEmitter = require('events'); var nconf = require('nconf'); var real; +var noCluster; +var singleHost; function get() { if (real) { @@ -13,14 +15,23 @@ function get() { var pubsub; if (nconf.get('isCluster') === 'false') { - pubsub = new EventEmitter(); - pubsub.publish = pubsub.emit.bind(pubsub); + if (noCluster) { + real = noCluster; + return real; + } + noCluster = new EventEmitter(); + noCluster.publish = noCluster.emit.bind(noCluster); + pubsub = noCluster; } else if (nconf.get('singleHostCluster')) { - pubsub = new EventEmitter(); + if (singleHost) { + real = singleHost; + return real; + } + singleHost = new EventEmitter(); if (!process.send) { - pubsub.publish = pubsub.emit.bind(pubsub); + singleHost.publish = singleHost.emit.bind(singleHost); } else { - pubsub.publish = function (event, data) { + singleHost.publish = function (event, data) { process.send({ action: 'pubsub', event: event, @@ -29,10 +40,11 @@ function get() { }; process.on('message', function (message) { if (message && typeof message === 'object' && message.action === 'pubsub') { - pubsub.emit(message.event, message.data); + singleHost.emit(message.event, message.data); } }); } + pubsub = singleHost; } else if (nconf.get('redis')) { pubsub = require('./database/redis/pubsub'); } else if (nconf.get('mongo')) { @@ -55,4 +67,7 @@ module.exports = { removeAllListeners: function (event) { get().removeAllListeners(event); }, + reset: function () { + real = null; + }, }; diff --git a/test/pubsub.js b/test/pubsub.js index 1ae3eb5f4f..5fb082a210 100644 --- a/test/pubsub.js +++ b/test/pubsub.js @@ -7,27 +7,29 @@ var db = require('./mocks/databasemock'); var pubsub = require('../src/pubsub'); describe('pubsub', function () { - it('should use singleHostCluster', function (done) { - var oldValue = nconf.get('singleHostCluster'); - nconf.set('singleHostCluster', true); + it('should use the plain event emitter', function (done) { + nconf.set('isCluster', 'false'); + pubsub.reset(); pubsub.on('testEvent', function (message) { assert.equal(message.foo, 1); - nconf.set('singleHostCluster', oldValue); + nconf.set('isCluster', 'true'); pubsub.removeAllListeners('testEvent'); + pubsub.reset(); done(); }); pubsub.publish('testEvent', { foo: 1 }); }); - it('should use the current database\'s pubsub', function (done) { + it('should use singleHostCluster', function (done) { var oldValue = nconf.get('singleHostCluster'); - nconf.set('singleHostCluster', false); + nconf.set('singleHostCluster', true); pubsub.on('testEvent', function (message) { - assert.equal(message.foo, 1); + assert.equal(message.foo, 2); nconf.set('singleHostCluster', oldValue); pubsub.removeAllListeners('testEvent'); + pubsub.reset(); done(); }); - pubsub.publish('testEvent', { foo: 1 }); + pubsub.publish('testEvent', { foo: 2 }); }); });