@fanoutio/eventstream
Version:
Connect-compatible middleware that enables the easy creation of EventStream endpoints
37 lines (36 loc) • 1.21 kB
JavaScript
import { Readable } from 'stream';
import Debug from 'debug';
const debug = Debug('eventstream');
export default class AddressedEventsReadable extends Readable {
addressedEvents;
channels;
listenHandle;
constructor(addressedEvents, channels) {
super({
objectMode: true,
});
this.addressedEvents = addressedEvents;
debug('AddressedEventsReadable constructed with channels', channels);
this.channels = channels;
this.listenHandle = null;
}
_read(_size) {
debug('AddressedEventsReadable _read');
if (this.listenHandle == null) {
debug('AddressedEventsReadable setting up listener');
this.listenHandle = this.addressedEvents.addListener((addressedEvent) => {
if (this.channels.includes(addressedEvent.channel)) {
this.push(addressedEvent.event);
}
});
}
}
_destroy(error, callback) {
debug('AddressedEventsReadable _destroy');
if (this.listenHandle != null) {
this.listenHandle();
this.listenHandle = null;
}
super._destroy(error, callback);
}
}