How do I implement topic hierarchies using the chat API in Javascript?

63 Views Asked by At

I'd like to create topic-based chat or nested topics in a Javascript-based chat API, allowing users to subscribe to both parent and child topics at the same time.(Provide basic codes if possible through a link or direct code.)

1

There are 1 best solutions below

0
Antony berkmans On

Consider utilising a hierarchical naming convention for topics (e.g., "sports/football" and "sports/basketball") to support topic hierarchies in JavaScript. When a user subscribes to a parent subject ("sports"), utilise wildcard or pattern matching in your topic subscription logic to automatically subscribe them to all child topics ("sports/football," "sports/basketball").

Create topic await SDK.createTopic({ topicName: "", metaData: {} // Optional });

Example parent class: Sports Example child class: Basketball/football

Sample code (Replace your parent class and child class based on your topics)

class TopicManager {
  constructor() {
    this.topics = {};
  }

  subscribe(topic) {
    if (!this.topics[topic]) {
      this.topics[topic] = [];
    }
    return {
      publish: (message) => {
        this.topics[topic].forEach((subscriber) => {
          subscriber(message);
        });
      },
      unsubscribe: () => {
        const index = this.topics[topic].indexOf(subscriber);
        if (index !== -1) {
          this.topics[topic].splice(index, 1);
        }
      },
    };
  }

  subscribeWildcard(parentTopic, childTopic) {
    const wildcardTopic = `${parentTopic}/*`;
    if (!this.topics[wildcardTopic]) {
      this.topics[wildcardTopic] = [];
    }
    this.topics[wildcardTopic].push(childTopic);
  }
}

// Example usage:
const topicManager = new TopicManager();

const sportsTopic = topicManager.subscribe('sports');
const footballTopic = topicManager.subscribeWildcard('sports', 'sports/football');
const basketballTopic = topicManager.subscribeWildcard('sports', 'sports/basketball');

Code reference document