You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
4 years ago
|
import { EventEmitter } from 'events';
|
||
|
import cluster from 'cluster';
|
||
5 years ago
|
|
||
5 years ago
|
const bus = new EventEmitter();
|
||
4 years ago
|
|
||
4 years ago
|
export function subscribe(events, handler, funcName) {
|
||
4 years ago
|
if (!funcName) {
|
||
5 years ago
|
for (const event of events) bus.on(event, handler);
|
||
4 years ago
|
} else {
|
||
|
handler.__bus = (...args) => {
|
||
|
handler[funcName].call(handler, ...args);
|
||
|
};
|
||
|
for (const event of events) bus.on(event, handler.__bus);
|
||
|
}
|
||
|
}
|
||
|
|
||
4 years ago
|
export function unsubscribe(events, handler, funcName) {
|
||
4 years ago
|
if (!funcName) {
|
||
5 years ago
|
for (const event of events) bus.off(event, handler);
|
||
4 years ago
|
} else {
|
||
|
handler.__bus = (...args) => {
|
||
|
handler[funcName].call(handler, ...args);
|
||
|
};
|
||
4 years ago
|
// FIXME doesn't work
|
||
4 years ago
|
for (const event of events) bus.off(event, handler.__bus);
|
||
|
delete handler.__bus;
|
||
|
}
|
||
|
}
|
||
|
|
||
4 years ago
|
export function publish(event, payload, isMaster = true) {
|
||
4 years ago
|
// Process forked by pm2 would also have process.send
|
||
|
if (isMaster && process.send && !cluster.isMaster) {
|
||
4 years ago
|
process.send({
|
||
|
event: 'bus',
|
||
|
eventName: event,
|
||
|
payload,
|
||
4 years ago
|
});
|
||
4 years ago
|
} else {
|
||
|
bus.emit(event, { value: payload, event });
|
||
4 years ago
|
}
|
||
|
}
|
||
|
|
||
4 years ago
|
global.Hydro.service.bus = {
|
||
4 years ago
|
subscribe, unsubscribe, publish,
|
||
5 years ago
|
};
|