UNPKG

@tmorin/ceb-messaging-simple

Version:

The package is part of the `<ceb/>` library. It provides an implementation of the messaging model leveraging on a vanilla TypeScript/JavaScript environment.

65 lines 2.73 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; /** * The symbol used to register {@link SimpleEventBus}. */ export const SimpleEventBusSymbol = Symbol.for("ceb/inversion/SimpleEventBus"); export class SimpleEventBus { constructor(emitter, listeners = new Map()) { this.emitter = emitter; this.listeners = listeners; } get observe() { return this.emitter; } publish(...events) { events.forEach((event) => { var _a; this.emitter.emit("event_received", { bus: this, event, }); (_a = this.listeners.get(event.headers.messageType)) === null || _a === void 0 ? void 0 : _a.forEach((listener) => { Promise.resolve((() => __awaiter(this, void 0, void 0, function* () { return listener(event); }))()).catch((error) => this.emitter.emit("event_listener_failed", { bus: this, event, error, })); }); }); } subscribe(eventType, listener, options) { var _a; if (!this.listeners.has(eventType)) { this.listeners.set(eventType, new Set()); } const listenerWrapper = (event) => { var _a; if (options === null || options === void 0 ? void 0 : options.once) { (_a = this.listeners.get(eventType)) === null || _a === void 0 ? void 0 : _a.delete(listenerWrapper); } return listener(event); }; (_a = this.listeners.get(eventType)) === null || _a === void 0 ? void 0 : _a.add(listenerWrapper); return { remove: () => { var _a; (_a = this.listeners.get(eventType)) === null || _a === void 0 ? void 0 : _a.delete(listenerWrapper); }, }; } dispose() { return __awaiter(this, void 0, void 0, function* () { this.listeners.clear(); this.emitter.emit("disposed", { bus: this }); }); } } //# sourceMappingURL=event.js.map