UNPKG

nats-micro

Version:

NATS micro compatible extra-lightweight microservice library

41 lines 1.33 kB
export 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; } } //# sourceMappingURL=tokenEventEmitter.js.map