1 import {
2 EventBusTypes,
3 IEventBusModuleService,
4 Message,
5 Subscriber,
6 } from "@medusajs/framework/types"
7
8 /**
9 * In-memory event bus. Events are dispatched synchronously to the
10 * registered subscribers and every emitted message is recorded so tests
11 * can assert on the events the module published.
12 */
13 export class FakeEventBus implements IEventBusModuleService {
14 protected readonly subscribers_: Map<string | symbol, Set<Subscriber>> =
15 new Map()
16
17 emitted: Message[] = []
18
19 async emit<T>(
20 messages: Message<T> | Message<T>[],
21 options?: Record<string, unknown>
22 ): Promise<void> {
23 const messages_ = Array.isArray(messages) ? messages : [messages]
24
25 for (const message of messages_) {
26 this.emitted.push(message)
27
28 const subscribers = this.subscribers_.get(message.name)
29
30 for (const subscriber of subscribers ?? []) {
31 const { options, ...payload } = message
32 await subscriber(payload)
33 }
34 }
35 }
36
37 subscribe(event: string | symbol, subscriber: Subscriber): this {
38 const subscribers = this.subscribers_.get(event) ?? new Set()
39 subscribers.add(subscriber)
40 this.subscribers_.set(event, subscribers)
41 return this
42 }
43
44 unsubscribe(
45 event: string | symbol,
46 subscriber: Subscriber,
47 context?: EventBusTypes.SubscriberContext
48 ): this {
49 this.subscribers_.get(event)?.delete(subscriber)
50 return this
51 }
52
53 reset() {
54 this.emitted = []
55 }
56
57 async releaseGroupedEvents(eventGroupId: string): Promise<void> {}
58
59 async clearGroupedEvents(eventGroupId: string): Promise<void> {}
60 }