UNPKG

pub-sub-topic-ts

Version:
56 lines (55 loc) 1.52 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PubSub = void 0; const uuid_1 = require("uuid"); const subscriber_1 = require("./subscriber"); const topic_1 = require("./topic"); class PubSub { constructor() { this._topics = []; } publish(topicName, data) { const topic = this._topics.find(t => { return t.name === topicName; }); if (topic) { topic.publish(data); } } getTopics() { return this._topics.map(t => t.name); } deleteTopic(name) { this._topics = this._topics.filter(topic => { return topic.name !== name; }); } subscribe(name, callback) { const topic = this._topics.find(t => { return t.name === name; }); const subscriber = new subscriber_1.Subscriber(name, (0, uuid_1.v4)(), callback); if (topic) { topic.subscribe(subscriber); } else { const topic = this.createTopic(name); topic.subscribe(subscriber); } return subscriber; } createTopic(topic) { const newTopic = new topic_1.Topic(topic); this._topics.push(newTopic); return newTopic; } unsubscribe(subscriber) { const topic = this._topics.find(t => { return t.name === subscriber.topicName; }); if (topic) { topic.unsubscribe(subscriber); } } } exports.PubSub = PubSub;