Files
NodeBB/src/pubsub.js

72 lines
1.4 KiB
JavaScript
Raw Normal View History

2014-12-21 20:25:54 -05:00
'use strict';
var EventEmitter = require('events');
2017-02-17 20:20:42 -07:00
var nconf = require('nconf');
var real;
2018-10-17 14:20:15 -04:00
var noCluster;
var singleHost;
2014-12-21 20:25:54 -05:00
function get() {
if (real) {
return real;
}
var pubsub;
2014-12-21 20:25:54 -05:00
if (!nconf.get('isCluster')) {
2018-10-17 14:20:15 -04:00
if (noCluster) {
real = noCluster;
return real;
}
noCluster = new EventEmitter();
noCluster.publish = noCluster.emit.bind(noCluster);
pubsub = noCluster;
} else if (nconf.get('singleHostCluster')) {
2018-10-17 14:20:15 -04:00
if (singleHost) {
real = singleHost;
return real;
}
singleHost = new EventEmitter();
2018-10-13 20:28:18 -04:00
if (!process.send) {
2018-10-17 14:20:15 -04:00
singleHost.publish = singleHost.emit.bind(singleHost);
2018-10-13 20:28:18 -04:00
} else {
2018-10-17 14:20:15 -04:00
singleHost.publish = function (event, data) {
2018-10-13 18:26:08 -04:00
process.send({
action: 'pubsub',
event: event,
data: data,
});
2018-10-13 20:28:18 -04:00
};
2021-02-04 00:01:39 -07:00
process.on('message', (message) => {
2018-10-13 20:28:18 -04:00
if (message && typeof message === 'object' && message.action === 'pubsub') {
2018-10-17 14:20:15 -04:00
singleHost.emit(message.event, message.data);
2018-10-13 20:28:18 -04:00
}
});
}
2018-10-17 14:20:15 -04:00
pubsub = singleHost;
} else if (nconf.get('redis')) {
2018-01-22 16:41:22 -05:00
pubsub = require('./database/redis/pubsub');
} else {
throw new Error('[[error:redis-required-for-pubsub]]');
2014-12-21 20:25:54 -05:00
}
real = pubsub;
return pubsub;
}
module.exports = {
publish: function (event, data) {
get().publish(event, data);
},
on: function (event, callback) {
get().on(event, callback);
},
removeAllListeners: function (event) {
get().removeAllListeners(event);
},
2018-10-17 14:20:15 -04:00
reset: function () {
real = null;
},
};