ravendb
Version:
RavenDB client for Node.js
93 lines • 3.02 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ChangesObservable = void 0;
class ChangesObservable {
_type;
_connectionState;
_filter;
_subscribers = new Set();
_errorSubscribers = new Set();
_sendHandler;
_errorHandler;
constructor(type, connectionState, filter) {
this._type = type;
this._connectionState = connectionState;
this._filter = filter;
}
on(event, handler) {
switch (event) {
case "data": {
// since allow multiple subscriptions on single object we cant register it multiple times
// to avoid duplicates in notification
if (!this._sendHandler) {
// register shared handler
this._sendHandler = (payload) => this.send(payload);
this._connectionState.addOnChangeNotification(this._type, this._sendHandler);
}
this._subscribers.add(handler);
this._connectionState.inc();
break;
}
case "error": {
if (!this._errorHandler) {
// register shared error handler
this._errorHandler = (ex) => this.error(ex);
this._connectionState.addOnError(this._errorHandler);
}
this._errorSubscribers.add(handler);
break;
}
}
return this;
}
removeListener(event, handler) {
return this.off(event, handler);
}
off(event, handler) {
switch (event) {
case "data": {
if (this._subscribers.delete(handler)) {
this._connectionState.dec();
}
if (!this._subscribers.size) {
// no more subscribers left - remove from parent
this._connectionState.removeOnChangeNotification(this._type, this._sendHandler);
this._sendHandler = undefined;
}
break;
}
case "error": {
this._errorSubscribers.delete(handler);
if (!this._errorSubscribers.size) {
this._connectionState.removeOnError(this._errorHandler);
this._errorHandler = undefined;
}
break;
}
}
return this;
}
send(msg) {
try {
if (!this._filter(msg)) {
return;
}
}
catch (e) {
this.error(e);
return;
}
for (const x of this._subscribers)
x(msg);
}
error(e) {
for (const x of this._errorSubscribers) {
x(e);
}
}
ensureSubscribedNow() {
return this._connectionState.ensureSubscribedNow();
}
}
exports.ChangesObservable = ChangesObservable;
//# sourceMappingURL=ChangesObservable.js.map