|
1
|
import { |
|
2
|
EventBusTypes, |
|
3
|
EventMetadata, |
|
4
|
InterceptorSubscriber, |
|
5
|
InternalModuleDeclaration, |
|
6
|
} from "@medusajs/types" |
|
7
|
import { ulid } from "ulid" |
|
8
|
|
|
9
|
export abstract class AbstractEventBusModuleService |
|
10
|
implements EventBusTypes.IEventBusModuleService |
|
11
|
{ |
|
12
|
protected isWorkerMode: boolean = true |
|
13
|
|
|
14
|
protected eventToSubscribersMap_: Map< |
|
15
|
string | symbol, |
|
16
|
EventBusTypes.SubscriberDescriptor[] |
|
17
|
> = new Map() |
|
18
|
|
|
19
|
protected interceptorSubscribers_: Set<InterceptorSubscriber> = new Set() |
|
20
|
|
|
21
|
public get eventToSubscribersMap(): Map< |
|
22
|
string | symbol, |
|
23
|
EventBusTypes.SubscriberDescriptor[] |
|
24
|
> { |
|
25
|
return this.eventToSubscribersMap_ |
|
26
|
} |
|
27
|
|
|
28
|
protected constructor( |
|
29
|
cradle: Record<string, unknown>, |
|
30
|
moduleOptions = {}, |
|
31
|
moduleDeclaration: InternalModuleDeclaration |
|
32
|
) { |
|
33
|
this.isWorkerMode = moduleDeclaration.worker_mode !== "server" |
|
34
|
} |
|
35
|
|
|
36
|
abstract emit<T>( |
|
37
|
data: EventBusTypes.Message<T> | EventBusTypes.Message<T>[], |
|
38
|
options: Record<string, unknown> |
|
39
|
): Promise<void> |
|
40
|
|
|
41
|
/* |
|
42
|
Grouped events are useful when you have distributed transactions |
|
43
|
where you need to explicitly group, release and clear events upon |
|
44
|
lifecycle events of a transaction. |
|
45
|
*/ |
|
46
|
// Given a eventGroupId, all the grouped events will be released |
|
47
|
abstract releaseGroupedEvents(eventGroupId: string): Promise<void> |
|
48
|
|
|
49
|
// Given a eventGroupId, all the grouped events will be cleared unless eventNames are provided |
|
50
|
// If eventNames are provided, only the events that match the eventNames will be cleared from the |
|
51
|
// group |
|
52
|
abstract clearGroupedEvents( |
|
53
|
eventGroupId: string, |
|
54
|
options?: { |
|
55
|
eventNames?: string[] |
|
56
|
} |
|
57
|
): Promise<void> |
|
58
|
|
|
59
|
protected storeSubscribers({ |
|
60
|
event, |
|
61
|
subscriberId, |
|
62
|
subscriber, |
|
63
|
}: { |
|
64
|
event: string | symbol |
|
65
|
subscriberId: string |
|
66
|
subscriber: EventBusTypes.Subscriber |
|
67
|
}) { |
|
68
|
const newSubscriberDescriptor = { subscriber, id: subscriberId } |
|
69
|
|
|
70
|
const existingSubscribers = this.eventToSubscribersMap_.get(event) ?? [] |
|
71
|
|
|
72
|
const subscriberAlreadyExists = existingSubscribers.find( |
|
73
|
(sub) => sub.id === subscriberId |
|
74
|
) |
|
75
|
|
|
76
|
if (subscriberAlreadyExists) { |
|
77
|
throw Error(`Subscriber with id ${subscriberId} already exists`) |
|
78
|
} |
|
79
|
|
|
80
|
this.eventToSubscribersMap_.set(event, [ |
|
81
|
...existingSubscribers, |
|
82
|
newSubscriberDescriptor, |
|
83
|
]) |
|
84
|
} |
|
85
|
|
|
86
|
public subscribe( |
|
87
|
eventName: string | symbol, |
|
88
|
subscriber: EventBusTypes.Subscriber, |
|
89
|
context?: EventBusTypes.SubscriberContext |
|
90
|
): this { |
|
91
|
if (typeof subscriber !== `function`) { |
|
92
|
throw new Error("Subscriber must be a function") |
|
93
|
} |
|
94
|
/** |
|
95
|
* If context is provided, we use the subscriberId from it |
|
96
|
* otherwise we generate a random using a ulid |
|
97
|
*/ |
|
98
|
|
|
99
|
const event = eventName.toString() |
|
100
|
const subscriberId = context?.subscriberId ?? `${event}-${ulid()}` |
|
101
|
|
|
102
|
;(subscriber as any).subscriberId = subscriberId |
|
103
|
|
|
104
|
this.storeSubscribers({ |
|
105
|
event, |
|
106
|
subscriberId, |
|
107
|
subscriber, |
|
108
|
}) |
|
109
|
|
|
110
|
return this |
|
111
|
} |
|
112
|
|
|
113
|
unsubscribe( |
|
114
|
eventName: string | symbol, |
|
115
|
subscriber: EventBusTypes.Subscriber, |
|
116
|
context?: EventBusTypes.SubscriberContext |
|
117
|
): this { |
|
118
|
if (!this.isWorkerMode) { |
|
119
|
return this |
|
120
|
} |
|
121
|
|
|
122
|
const existingSubscribers = this.eventToSubscribersMap_.get(eventName) |
|
123
|
const subscriberId = |
|
124
|
context?.subscriberId ?? (subscriber as any).subscriberId |
|
125
|
|
|
126
|
if (existingSubscribers?.length) { |
|
127
|
const subIndex = existingSubscribers?.findIndex( |
|
128
|
(sub) => sub.id === subscriberId |
|
129
|
) |
|
130
|
|
|
131
|
if (subIndex !== -1) { |
|
132
|
this.eventToSubscribersMap_ |
|
133
|
.get(eventName) |
|
134
|
?.splice(subIndex as number, 1) |
|
135
|
} |
|
136
|
} |
|
137
|
|
|
138
|
return this |
|
139
|
} |
|
140
|
|
|
141
|
/** |
|
142
|
* Add an interceptor subscriber that receives all messages before they are emitted |
|
143
|
* |
|
144
|
* @param interceptor - Function that receives messages before emission |
|
145
|
* @returns this for chaining |
|
146
|
*/ |
|
147
|
public addInterceptor(interceptor: InterceptorSubscriber): this { |
|
148
|
this.interceptorSubscribers_.add(interceptor) |
|
149
|
return this |
|
150
|
} |
|
151
|
|
|
152
|
/** |
|
153
|
* Remove an interceptor subscriber |
|
154
|
* |
|
155
|
* @param interceptor - Function to remove from interceptors |
|
156
|
* @returns this for chaining |
|
157
|
*/ |
|
158
|
public removeInterceptor(interceptor: InterceptorSubscriber): this { |
|
159
|
this.interceptorSubscribers_.delete(interceptor) |
|
160
|
return this |
|
161
|
} |
|
162
|
|
|
163
|
/** |
|
164
|
* Call all interceptor subscribers with the message before emission |
|
165
|
* This should be called by implementations before emitting events |
|
166
|
* |
|
167
|
* @param message - The message to be intercepted |
|
168
|
* @param context - Optional context about the emission |
|
169
|
*/ |
|
170
|
protected async callInterceptors<T = unknown>( |
|
171
|
message: EventBusTypes.Message<T>, |
|
172
|
context?: { isGrouped?: boolean; eventGroupId?: string } |
|
173
|
): Promise<void> { |
|
174
|
Array.from(this.interceptorSubscribers_).map(async (interceptor) => { |
|
175
|
try { |
|
176
|
await interceptor(message, context) |
|
177
|
} catch (error) { |
|
178
|
// Log error but don't stop other interceptors or the emission |
|
179
|
console.error("Error in event bus interceptor:", error) |
|
180
|
} |
|
181
|
}) |
|
182
|
} |
|
183
|
|
|
184
|
/** |
|
185
|
* Adds `created_at` to event metadata when an event is emitted. |
|
186
|
*/ |
|
187
|
protected withCreatedAtMetadata(metadata?: EventMetadata): EventMetadata { |
|
188
|
return { |
|
189
|
...metadata, |
|
190
|
created_at: new Date(), |
|
191
|
} |
|
192
|
} |
|
193
|
|
|
194
|
/** |
|
195
|
* Adds `published_at` to event metadata when an event is published to the event bus. |
|
196
|
*/ |
|
197
|
protected withPublishedAtMetadata(metadata?: EventMetadata): EventMetadata { |
|
198
|
return { |
|
199
|
...metadata, |
|
200
|
published_at: new Date(), |
|
201
|
} |
|
202
|
} |
|
203
|
|
|
204
|
/** |
|
205
|
* Parses date metadata fields after JSON serialization. |
|
206
|
*/ |
|
207
|
protected parseEventMetadataDates( |
|
208
|
metadata?: EventMetadata |
|
209
|
): EventMetadata | undefined { |
|
210
|
if (!metadata) { |
|
211
|
return metadata |
|
212
|
} |
|
213
|
|
|
214
|
return { |
|
215
|
...metadata, |
|
216
|
...(metadata.created_at != null |
|
217
|
? { |
|
218
|
created_at: new Date(metadata.created_at), |
|
219
|
} |
|
220
|
: {}), |
|
221
|
...(metadata.published_at != null |
|
222
|
? { |
|
223
|
published_at: new Date(metadata.published_at), |
|
224
|
} |
|
225
|
: {}), |
|
226
|
} |
|
227
|
} |
|
228
|
} |
|
229
|
|
|
230
|
export * from "./build-event-messages" |
|
231
|
export * from "./common-events" |
|
232
|
export * from "./message-aggregator" |
|
233
|
export * from "./utils" |