|
1
|
import { Context, EventBusTypes } from "@medusajs/types" |
|
2
|
import { buildModuleResourceEventName } from "../event-bus/utils" |
|
3
|
|
|
4
|
// TODO should that move closer to the event bus? and maybe be rename to modulemoduleEventBuilderFactory |
|
5
|
|
|
6
|
/** |
|
7
|
* |
|
8
|
* Factory function to create event builders for different entities |
|
9
|
* |
|
10
|
* @example |
|
11
|
* const createdFulfillment = moduleEventBuilderFactory({ |
|
12
|
* source: Modules.FULFILLMENT, |
|
13
|
* action: CommonEvents.CREATED, |
|
14
|
* object: "fulfillment", |
|
15
|
* eventsEnum: FulfillmentEvents, |
|
16
|
* }) |
|
17
|
* |
|
18
|
* createdFulfillment({ |
|
19
|
* data, |
|
20
|
* sharedContext, |
|
21
|
* }) |
|
22
|
* |
|
23
|
* @param action |
|
24
|
* @param object |
|
25
|
* @param eventsEnum |
|
26
|
* @param service |
|
27
|
*/ |
|
28
|
export function moduleEventBuilderFactory({ |
|
29
|
action, |
|
30
|
object, |
|
31
|
eventName, |
|
32
|
source, |
|
33
|
}: { |
|
34
|
action: string |
|
35
|
object: string |
|
36
|
eventName?: string |
|
37
|
source: string |
|
38
|
}) { |
|
39
|
return function ({ |
|
40
|
data, |
|
41
|
sharedContext, |
|
42
|
}: { |
|
43
|
data: { id: string } | { id: string }[] |
|
44
|
sharedContext: Context |
|
45
|
}) { |
|
46
|
data = Array.isArray(data) ? data : [data] |
|
47
|
|
|
48
|
if (!data.length) { |
|
49
|
return |
|
50
|
} |
|
51
|
|
|
52
|
const aggregator = sharedContext.messageAggregator! |
|
53
|
const messages: EventBusTypes.RawMessageFormat[] = [] |
|
54
|
|
|
55
|
if (!eventName) { |
|
56
|
eventName = buildModuleResourceEventName({ |
|
57
|
prefix: source, |
|
58
|
objectName: object, |
|
59
|
action, |
|
60
|
}) |
|
61
|
} |
|
62
|
|
|
63
|
messages.push({ |
|
64
|
source, |
|
65
|
action, |
|
66
|
context: sharedContext, |
|
67
|
data: { |
|
68
|
id: data.length === 1 ? data[0].id : data.map((item) => item.id), |
|
69
|
}, |
|
70
|
eventName: eventName!, |
|
71
|
object, |
|
72
|
}) |
|
73
|
|
|
74
|
aggregator.saveRawMessageData(messages) |
|
75
|
} |
|
76
|
} |