mirror of
https://gitcode.com/gh_mirrors/hy/Hydro.git
synced 2026-10-17 09:36:08 +08:00
46 lines
1.2 KiB
JavaScript
46 lines
1.2 KiB
JavaScript
const { EventEmitter } = require('events');
|
|
const cluster = require('cluster');
|
|
|
|
const bus = new EventEmitter();
|
|
|
|
function subscribe(events, handler, funcName) {
|
|
if (!funcName) {
|
|
for (const event of events) bus.on(event, handler);
|
|
} else {
|
|
handler.__bus = (...args) => {
|
|
handler[funcName].call(handler, ...args);
|
|
};
|
|
for (const event of events) bus.on(event, handler.__bus);
|
|
}
|
|
}
|
|
|
|
function unsubscribe(events, handler, funcName) {
|
|
if (!funcName) {
|
|
for (const event of events) bus.off(event, handler);
|
|
} else {
|
|
handler.__bus = (...args) => {
|
|
handler[funcName].call(handler, ...args);
|
|
};
|
|
// FIXME doesn't work
|
|
for (const event of events) bus.off(event, handler.__bus);
|
|
delete handler.__bus;
|
|
}
|
|
}
|
|
|
|
function publish(event, payload, isMaster = true) {
|
|
// Process forked by pm2 would also have process.send
|
|
if (isMaster && process.send && !cluster.isMaster) {
|
|
process.send({
|
|
event: 'bus',
|
|
eventName: event,
|
|
payload,
|
|
});
|
|
} else {
|
|
bus.emit(event, { value: payload, event });
|
|
}
|
|
}
|
|
|
|
global.Hydro.service.bus = module.exports = {
|
|
subscribe, unsubscribe, publish,
|
|
};
|