diff --git a/src/shared/infrastructure/events/InMemoryEventPublisher.ts b/src/shared/infrastructure/events/InMemoryEventPublisher.ts index 8b045eaf..1505f535 100644 --- a/src/shared/infrastructure/events/InMemoryEventPublisher.ts +++ b/src/shared/infrastructure/events/InMemoryEventPublisher.ts @@ -3,7 +3,10 @@ import { IDomainEvent } from '../../domain/events/IDomainEvent'; import { Result, ok } from '../../core/Result'; export class InMemoryEventPublisher implements IEventPublisher { - private static subscribers: Map Promise>> = new Map(); + private static subscribers: Map< + string, + Array<(event: IDomainEvent) => Promise> + > = new Map(); async publishEvents(events: IDomainEvent[]): Promise> { for (const event of events) { @@ -13,8 +16,9 @@ export class InMemoryEventPublisher implements IEventPublisher { } private async publishSingleEvent(event: IDomainEvent): Promise { - const handlers = InMemoryEventPublisher.subscribers.get(event.eventName) || []; - + const handlers = + InMemoryEventPublisher.subscribers.get(event.eventName) || []; + // Process handlers asynchronously but don't wait for them // This simulates the async nature of real message queues setImmediate(async () => { @@ -28,7 +32,10 @@ export class InMemoryEventPublisher implements IEventPublisher { }); } - static addSubscriber(eventType: string, handler: (event: IDomainEvent) => Promise): void { + static addSubscriber( + eventType: string, + handler: (event: IDomainEvent) => Promise, + ): void { if (!this.subscribers.has(eventType)) { this.subscribers.set(eventType, []); } diff --git a/src/shared/infrastructure/events/InMemoryEventSubscriber.ts b/src/shared/infrastructure/events/InMemoryEventSubscriber.ts index 119cb586..d6667405 100644 --- a/src/shared/infrastructure/events/InMemoryEventSubscriber.ts +++ b/src/shared/infrastructure/events/InMemoryEventSubscriber.ts @@ -15,14 +15,17 @@ export class InMemoryEventSubscriber implements IEventSubscriber { handler: IEventHandler, ): Promise { this.handlers.set(eventType, handler); - + // Register with the static publisher - InMemoryEventPublisher.addSubscriber(eventType, async (event: IDomainEvent) => { - const result = await handler.handle(event as T); - if (result.isErr()) { - throw result.error; - } - }); + InMemoryEventPublisher.addSubscriber( + eventType, + async (event: IDomainEvent) => { + const result = await handler.handle(event as T); + if (result.isErr()) { + throw result.error; + } + }, + ); } async start(): Promise {