All files / application/services DomainEventPublisher.ts

76.92% Statements 10/13
66.66% Branches 4/6
50% Functions 2/4
83.33% Lines 10/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33          31x     29x 29x 29x   29x                 14x   14x 21x 21x   2x          
import { DomainEvent } from "../../domain/events/DomainEvent";
 
type EventHandler = (event: DomainEvent) => Promise<void> | void;
 
export class DomainEventPublisher {
  private handlers: Map<string, EventHandler[]> = new Map();
 
  subscribe(eventType: string, handler: EventHandler): () => void {
    const handlers = this.handlers.get(eventType) || [];
    handlers.push(handler);
    this.handlers.set(eventType, handlers);
 
    return () => {
      // Unsubscribe logic to remove the handler and prevent memory leaks
      const updatedHandlers =
        this.handlers.get(eventType)?.filter((h) => h !== handler) || [];
      this.handlers.set(eventType, updatedHandlers);
    };
  }
 
  async publish(event: DomainEvent): Promise<void> {
    const handlers = this.handlers.get(event.eventType) || [];
 
    for (const handler of handlers) {
      try {
        await handler(event);
      } catch (error) {
        console.error(`Error handling event ${event.eventType}:`, error);
      }
    }
  }
}