UNPKG

observer-ax

Version:
73 lines (61 loc) 2.51 kB
import { EventBus } from './EventBus'; import { NotifyObject } from '../models/NotifyObject.model'; import { ReceiverBus } from './Receiver'; import { ItemBus } from '../models/Item.model'; export class EventConcreteBus implements EventBus { private _receivers: { [key: string]: ReceiverBus[] } = {}; private _items: ItemBus[] = []; constructor(private defaultTriesCount: number = 3) { } protected getTopicReceivers(topic: string = 'ALL'): ReceiverBus[] { if (!this._receivers[topic]) { return []; } return this._receivers[topic]; } protected retryPublish(topic: string, subject: NotifyObject, receiver: ReceiverBus, tries: number) { for (var i = 0; i < tries; i++) { try { receiver.receive(subject, { topic: topic, pendingItems: this._items.length }); break; } catch (error) { console.error(error); } } } public async publish(subject: NotifyObject, topic: string = 'ALL', tries: number = 0): Promise<void> { if (tries === 0) { tries = this.defaultTriesCount; } const receivers = this.getTopicReceivers(topic); receivers.map((receiver: ReceiverBus) => new Promise(resolve => resolve(this.retryPublish(topic, subject, receiver, tries))),); } public async publishNow(): Promise<void> { while (this._items.length > 0) { const item = this._items.shift() as ItemBus; const receivers = this.getTopicReceivers(item.topic); if (receivers.length > 0) { receivers.map((receiver: ReceiverBus) => new Promise(resolve => resolve(this.retryPublish(item.topic, item.data, receiver, item.tries)))); } } } public subscribe(receiver: ReceiverBus, topic: string = 'ALL') { if (!this._receivers[topic]) { this._receivers[topic] = []; } this._receivers[topic].push(receiver); } public unsubscribe(receiver: ReceiverBus, topic: string = 'ALL') { if (!this._receivers[topic]) { return; } this._receivers[topic] = this._receivers[topic].filter(item => item !== receiver); } get receivers(): any { return this._receivers; } set items(values: ItemBus[]) { this._items.push(...values); } }