@lppedd/message-bus - v0.9.1
    Preparing search index...

    Interface MessageBus

    The message bus API.

    interface MessageBus {
        isDisposed: boolean;
        addInterceptor(interceptor: MessageInterceptor): void;
        addListener(listener: MessageListener): void;
        createChildBus(options?: Partial<ChildMessageBusOptions>): MessageBus;
        dispose(): void;
        publish(topic: Topic<void, void>): void;
        publish<T>(topic: Topic<T, void>, data: Strict<T>): void;
        publishAsync<R = void>(topic: UnicastTopic<void, R>): Promise<R>;
        publishAsync<R = void>(topic: Topic<void, R>): Promise<R[]>;
        publishAsync<T, R = void>(
            topic: UnicastTopic<T, R>,
            data: Strict<T>,
        ): Promise<R>;
        publishAsync<T, R = void>(
            topic: Topic<T, R>,
            data: Strict<T>,
        ): Promise<R[]>;
        removeInterceptor(interceptor: MessageInterceptor): void;
        removeListener(listener: MessageListener): void;
        subscribe<T>(topic: Topic<T, void>): LazyAsyncSubscription<T>;
        subscribe<T extends [any, ...any[]]>(
            topics: Topics<T>,
        ): LazyAsyncSubscription<T[number]>;
        subscribe<T, R = void>(
            topic: Topic<T, R>,
            handler: MessageHandler<T, R>,
        ): Subscription;
        subscribe<T extends [any, ...any[]]>(
            topics: Topics<T>,
            handler: MessageHandler<T[number], void>,
        ): Subscription;
        subscribeInstance(instance: object): void;
        subscribeOnce<T>(topic: Topic<T, void>): Promise<T>;
        subscribeOnce<T extends [any, ...any[]]>(
            topics: Topics<T>,
        ): Promise<T[number]>;
        subscribeOnce<T, R = void>(
            topic: Topic<T, R>,
            handler: MessageHandler<T, R>,
        ): Subscription;
        subscribeOnce<T extends [any, ...any[]]>(
            topics: Topics<T>,
            handler: MessageHandler<T[number], void>,
        ): Subscription;
        unsubscribeInstance(instance: object): void;
        withLimit(limit: number): SubscriptionBuilder;
        withPriority(priority: number): SubscriptionBuilder;
    }
    Index

    Properties

    isDisposed: boolean

    Whether the message bus is disposed.

    Methods

    • Adds a new message interceptor to the bus.

      Message interceptors allow inspecting, modifying, or vetoing messages before they are dispatched to subscribed handlers.

      Interceptors are invoked in reverse order of registration: the most recently added interceptor will wrap all previously added ones.

      Parameters

      • interceptor: MessageInterceptor

        The interceptor to add.

      Returns void

    • Adds a message listener that will be notified of every message published on this message bus, regardless of topic.

      Listeners are invoked before any topic-specific subscribers. This allows observing messages even if no subscriber for a topic exists.

      Parameters

      Returns void

    • Disposes the message bus, all its child buses, and all active subscriptions.

      After disposal, neither this bus nor any child buses can be used for publishing or subscribing.

      Returns void

    • Publishes a new message without any associated data to the specified topic.

      Parameters

      • topic: Topic<void, void>

        The topic to publish the message to.

      Returns void

      messageBus.publish(PingTopic);
      
    • Publishes a new message with associated data to the specified topic.

      Type Parameters

      • T

      Parameters

      • topic: Topic<T, void>

        The topic to publish the message to.

      • data: Strict<T>

        The data payload to send with the message.

      Returns void

      messageBus.publish(CommandTopic, "shutdown");
      
    • Asynchronously publishes a new message without any associated data to the specified topic and waits for all subscribed handlers to complete.

      The returned promise resolves once all subscribed handlers have completed:

      • For unicast topics, it resolves to the single handler's result.
      • For multicast topics, it resolves to an array of all handler results.

      If one or more handlers throw, the promise is rejected:

      • With the original error if a single handler failed.
      • With an AggregateError containing all errors if multiple handlers failed.

      Type Parameters

      • R = void

      Parameters

      • topic: UnicastTopic<void, R>

        The topic to publish the message to.

      Returns Promise<R>

      A promise that resolves with the handler result(s), or rejects if any handler throws.

      // UnicastTopic
      const user = await bus.publishAsync(UserTopic);

      // Topic
      const statuses = await bus.publishAsync(ServiceStatusTopic);
      console.log("All service statuses", statuses);
    • Type Parameters

      • R = void

      Parameters

      Returns Promise<R[]>

    • Asynchronously publishes a new message with associated data to the specified topic and waits for all subscribed handlers to complete.

      The returned promise resolves once all subscribed handlers have completed:

      • For unicast topics, it resolves to the single handler's result.
      • For multicast topics, it resolves to an array of all handler results.

      If one or more handlers throw, the promise is rejected:

      • With the original error if a single handler failed.
      • With an AggregateError containing all errors if multiple handlers failed.

      Type Parameters

      • T
      • R = void

      Parameters

      • topic: UnicastTopic<T, R>

        The topic to publish the message to.

      • data: Strict<T>

        The data payload to send with the message.

      Returns Promise<R>

      A promise that resolves with the handler result(s), or rejects if any handler throws.

      // UnicastTopic
      const result = await bus.publishAsync(NotifyUserTopic, user);
      console.log("Notification result", result);

      // Topic
      const results = await bus.publishAsync(CommandTopic, "shutdown");
      console.log("Service shutdown results", results);
    • Type Parameters

      • T
      • R = void

      Parameters

      Returns Promise<R[]>

    • Removes a previously added message interceptor.

      Parameters

      • interceptor: MessageInterceptor

        The interceptor to remove.

      Returns void

    • Creates a lazily-initialized subscription to the specified topic that is also an AsyncIterableIterator.

      This allows consuming published messages using the for await ... of syntax. If an async iteration completes or ends early (e.g., via break, return, or an error), the subscription is automatically disposed.

      The subscription is created lazily: the first call to next() or single() triggers the underlying registration. If the consumer never starts an iteration or never awaits a message, no subscription is created.

      Type Parameters

      • T

      Parameters

      • topic: Topic<T, void>

        The topic to subscribe to.

      Returns LazyAsyncSubscription<T>

      const subscription = messageBus.subscribe(CommandTopic);

      for await (const command of subscription) {
      switch (command) {
      case "shutdown":
      // ...
      break;
      case "restart":
      // ...
      break;
      }
      }
    • Type Parameters

      • T extends [any, ...any[]]

      Parameters

      Returns LazyAsyncSubscription<T[number]>

    • Subscribes to the specified topic with a callback.

      The subscription is established immediately, and you can call Subscription.dispose to unsubscribe.

      Type Parameters

      • T
      • R = void

      Parameters

      • topic: Topic<T, R>

        The topic to subscribe to.

      • handler: MessageHandler<T, R>

        A callback invoked on each topic message.

      Returns Subscription

      const subscription = messageBus.subscribe(CommandTopic, (command) => {
      switch (command) {
      case "shutdown":
      // ...
      break;
      case "restart":
      // ...
      break;
      }
      });

      // Later
      subscription.dispose();
    • Type Parameters

      • T extends [any, ...any[]]

      Parameters

      Returns Subscription

    • Creates subscriptions for the given instance using the topic metadata defined on its class's methods via @Topic()-decorated parameters.

      Each discovered method is bound to the instance and invoked whenever a message is published to its associated topic. Subscriptions are cleaned up automatically when the instance is garbage-collected, or when the instance is passed to unsubscribeInstance.

      Parameters

      • instance: object

        An instance whose class contains @Topic()-decorated methods.

      Returns void

      class CommandProcessor {
      // The Subscription parameter is optional.
      // If present, it must immediately follow the decorated parameter.
      onCommand(@CommandTopic() command: string, subscription: Subscription): void {
      if (command === "shutdown") {
      // ...
      subscription.dispose();
      }
      }
      }

      // The onCommand method will be registered as a CommandTopic handler
      const processor = new CommandProcessor();
      messageBus.subscribeInstance(processor);
    • Subscribes once to the specified topic, returning a promise that resolves with the next published message.

      The subscription will be automatically disposed after receiving the message. This allows awaiting a single message without manual subscription management.

      Type Parameters

      • T

      Parameters

      • topic: Topic<T, void>

        The topic to subscribe to.

      Returns Promise<T>

      const command = await messageBus.subscribeOnce(CommandTopic);
      console.log(`Received command: ${command}`);
    • Type Parameters

      • T extends [any, ...any[]]

      Parameters

      Returns Promise<T[number]>

    • Subscribes once to the specified topic with a callback.

      The callback is invoked with the next message, after which the subscription is disposed.

      Type Parameters

      • T
      • R = void

      Parameters

      • topic: Topic<T, R>

        The topic to subscribe to.

      • handler: MessageHandler<T, R>

        A callback invoked on the next topic message.

      Returns Subscription

      // Automatically unsubscribes after the next message
      messageBus.subscribeOnce(CommandTopic, (command) => {
      console.log(`Received command: ${command}`);
      });
    • Type Parameters

      • T extends [any, ...any[]]

      Parameters

      Returns Subscription

    • Disposes all subscriptions to topics previously registered for the given instance via subscribeInstance. Any method handler bound to the instance will no longer be invoked when messages are published to its associated topic.

      Parameters

      • instance: object

        An instance whose subscriptions should be disposed.

      Returns void

    • Sets the maximum number of messages to receive for the next subscription.

      When the specified limit is reached, the subscription is automatically disposed.

      Parameters

      • limit: number

        The maximum number of messages to receive.

      Returns SubscriptionBuilder

    • Sets the priority for the next subscription.

      Higher priority (lower number) subscriptions are notified before lower priority (higher value) ones. The default priority value is 1.

      Parameters

      • priority: number

        A priority value, where a lower number means higher priority.

      Returns SubscriptionBuilder