nats-micro
Version:
NATS micro compatible extra-lightweight microservice library
45 lines • 1.48 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.TokenEventEmitter = void 0;
class TokenEventEmitter {
constructor() {
this.handlers = [];
}
on(wildcard, handler) {
this.handlers.push({ wildcard, handler: handler, once: false });
}
once(wildcard, handler) {
this.handlers.push({ wildcard, handler: handler, once: true });
}
off(wildcard, handler) {
const idx = this.handlers.findIndex((h) => h.wildcard === wildcard && h.handler === handler);
if (idx >= 0)
this.handlers.splice(idx, 1);
}
offAll() {
this.handlers.splice(0);
}
emit(subject, msg) {
for (const handler of [...this.handlers])
if (this.matchSubject(handler.wildcard, subject)) {
handler.handler(msg, subject);
if (handler.once)
this.off(handler.wildcard, handler.handler);
}
}
matchSubject(wildcard, subject) {
if (subject === wildcard)
return true;
const wildcardRegexp = new RegExp('^' +
wildcard
.replace('$', '\\$')
.replace('.', '\\.')
.replace('*', '[^\\.]+')
.replace('>', '.+') +
'$');
const match = !!subject.match(wildcardRegexp);
return match;
}
}
exports.TokenEventEmitter = TokenEventEmitter;
//# sourceMappingURL=tokenEventEmitter.js.map