Bus for publishing events to their handlers.

Supports multiple handlers for the same event type (pub/sub pattern).

// Register handlers
eventBus.subscribe(UserCreatedEvent, new SendWelcomeEmailHandler());
eventBus.subscribe(UserCreatedEvent, new UpdateStatisticsHandler());

// Publish event
await eventBus.publish(
new UserCreatedEvent('user-123', 'user@example.com')
);
interface EventBus {
    subscribe<TEvent extends Event>(
        eventType: new (...args: unknown[]) => TEvent,
        handler: EventHandler<TEvent>,
    ): void;
    publish(event: Event): Promise<void>;
    publishAll(events: Event[]): Promise<void>;
    unsubscribe<TEvent extends Event>(
        eventType: new (...args: unknown[]) => TEvent,
        handler: EventHandler<TEvent>,
    ): void;
}

Methods

  • Subscribes a handler to a specific event type.

    Multiple handlers can subscribe to the same event type.

    Type Parameters

    • TEvent extends Event

      The type of event

    Parameters

    • eventType: new (...args: unknown[]) => TEvent

      The event class or identifier

    • handler: EventHandler<TEvent>

      The handler for this event type

    Returns void

    eventBus.subscribe(
    UserCreatedEvent,
    new SendWelcomeEmailHandler()
    );
  • Publishes a single event to all subscribed handlers.

    Handlers are executed in parallel.

    Parameters

    • event: Event

      The event to publish

    Returns Promise<void>

    const event = new UserCreatedEvent('user-123', 'user@example.com');
    await eventBus.publish(event);
  • Publishes multiple events to all subscribed handlers.

    Events are published in order, but handlers within each event are executed in parallel.

    Parameters

    • events: Event[]

      The events to publish

    Returns Promise<void>

    await eventBus.publishAll([
    new UserCreatedEvent('user-123', 'user@example.com'),
    new WelcomeEmailSentEvent('user-123')
    ]);
  • Unsubscribes a handler from a specific event type.

    Type Parameters

    • TEvent extends Event

      The type of event

    Parameters

    • eventType: new (...args: unknown[]) => TEvent

      The event class or identifier

    • handler: EventHandler<TEvent>

      The handler to unsubscribe

    Returns void

    eventBus.unsubscribe(UserCreatedEvent, handler);