feat(fulfillment): Events management (#6730)

**What**
This pr includes some cleanup and refactoring around the abstract event emitter method for the module service to not rely on a named class property but instead on resolution naming.

Includes fulfillment set events on creation. 

The idea is that if that pr allows us to align and agreed on the approach as well as including the cleanup for other pr to use, If this gets merged I ll continue with another pr to do the rest of the event management


partially fix CORE-1735
This commit is contained in:
Adrien de Peretti
2024-03-20 12:44:26 +00:00
committed by GitHub
parent 06f22bb48a
commit c658bd0233
12 changed files with 356 additions and 19 deletions
@@ -13,19 +13,21 @@ export function buildEventMessages<T>(
options?: Record<string, unknown>
): EventBusTypes.Message<T>[] {
const messageData_ = Array.isArray(messageData) ? messageData : [messageData]
const messages: EventBusTypes.Message<T>[] = []
const messages: EventBusTypes.Message<any>[] = []
messageData_.map((data) => {
const data_ = Array.isArray(data.data) ? data.data : [data.data]
data_.forEach((bodyData) => {
const message = {
eventName: data.eventName,
body: {
metadata: data.metadata,
data: bodyData,
},
const message = composeMessage(data.eventName, {
data: bodyData,
service: data.metadata.service,
entity: data.metadata.object,
action: data.metadata.action,
context: {
eventGroupId: data.metadata.eventGroupId,
} as Context,
options,
}
})
messages.push(message)
})
})
+1
View File
@@ -106,3 +106,4 @@ export abstract class AbstractEventBusModuleService
export * from "./build-event-messages"
export * from "./common-events"
export * from "./message-aggregator"
export * from "./utils"
+86
View File
@@ -0,0 +1,86 @@
import { camelToSnakeCase, kebabCase, lowerCaseFirst } from "../common"
import { CommonEvents } from "./common-events"
import { KebabCase, SnakeCase } from "@medusajs/types"
type ReturnType<TNames extends string[]> = TNames extends [
infer TFirstName,
...infer TRest
]
? {
[K in Lowercase<CommonEvents>]: `${KebabCase<TFirstName & string>}.${K}`
} & {
[K in TRest[number] as `${SnakeCase<K & string>}_created`]: `${KebabCase<
K & string
>}.created`
} & {
[K in TRest[number] as `${SnakeCase<K & string>}_updated`]: `${KebabCase<
K & string
>}.updated`
} & {
[K in TRest[number] as `${SnakeCase<K & string>}_deleted`]: `${KebabCase<
K & string
>}.deleted`
} & {
[K in TRest[number] as `${SnakeCase<K & string>}_restored`]: `${KebabCase<
K & string
>}.restored`
} & {
[K in TRest[number] as `${SnakeCase<K & string>}_attached`]: `${KebabCase<
K & string
>}.attached`
} & {
[K in TRest[number] as `${SnakeCase<K & string>}_detached`]: `${KebabCase<
K & string
>}.detached`
}
: {}
/**
* From the given strings it will produce the event names accordingly.
* the result will look like:
* input: 'serviceZone'
* output: {
* created: 'fulfillment-set.created',
* updated: 'fulfillment-set.updated',
* deleted: 'fulfillment-set.deleted',
* restored: 'fulfillment-set.restored',
* attached: 'fulfillment-set.attached',
* detached: 'fulfillment-set.detached',
* service_zone_created: 'service-zone.created',
* service_zone_updated: 'service-zone.updated',
* service_zone_deleted: 'service-zone.deleted',
* service_zone_restored: 'service-zone.restored',
* service_zone_attached: 'service-zone.attached',
* service_zone_detached: 'service-zone.detached',
* ...
* }
*
* @param names
*/
export function buildEventNamesFromEntityName<TNames extends string[]>(
names: TNames
): ReturnType<TNames> {
const events = {}
for (let i = 0; i < names.length; i++) {
const name = names[i]
const snakedCaseName = lowerCaseFirst(camelToSnakeCase(name))
const kebabCaseName = lowerCaseFirst(kebabCase(name))
if (i === 0) {
for (const event of Object.values(CommonEvents) as string[]) {
events[event] = `${kebabCaseName}.${event}`
}
continue
}
for (const event of Object.values(CommonEvents) as string[]) {
events[`${snakedCaseName}_${event}`] =
`${kebabCaseName}.${event}` as `${KebabCase<
typeof name
>}.${typeof event}`
}
}
return events as ReturnType<TNames>
}
+21
View File
@@ -0,0 +1,21 @@
import { buildEventNamesFromEntityName } from "../event-bus"
const eventBaseNames: [
"fulfillmentSet",
"serviceZone",
"geoZone",
"shippingOption",
"shippingProfile",
"shippingOptionRule",
"fulfillment"
] = [
"fulfillmentSet",
"serviceZone",
"geoZone",
"shippingOption",
"shippingProfile",
"shippingOptionRule",
"fulfillment",
]
export const FulfillmentEvents = buildEventNamesFromEntityName(eventBaseNames)
+1
View File
@@ -1,3 +1,4 @@
export * from "./geo-zone"
export * from "./shipping-options"
export * from "./provider"
export * from "./events"
@@ -12,11 +12,11 @@ import {
SoftDeleteReturn,
} from "@medusajs/types"
import {
MapToConfig,
isString,
kebabCase,
lowerCaseFirst,
mapObjectTo,
MapToConfig,
pluralize,
upperCaseFirst,
} from "../common"
@@ -467,11 +467,19 @@ export function abstractModuleServiceFactory<
this.__container__ = container
this.baseRepository_ = container.baseRepository
try {
this.eventBusModuleService_ = container.eventBusModuleService
} catch {
/* ignore */
}
const hasEventBusModuleService = Object.keys(this.__container__).find(
// TODO: Should use ModuleRegistrationName.EVENT_BUS but it would require to move it to the utils package to prevent circular dependencies
(key) => key === "eventBusModuleService"
)
const hasEventBusService = Object.keys(this.__container__).find(
(key) => key === "eventBusService"
)
this.eventBusModuleService_ = hasEventBusService
? this.__container__.eventBusService
: hasEventBusModuleService
? this.__container__.eventBusModuleService
: undefined
}
protected async emitEvents_(groupedEvents) {
@@ -481,7 +489,7 @@ export function abstractModuleServiceFactory<
const promises: Promise<void>[] = []
for (const group of Object.keys(groupedEvents)) {
promises.push(this.eventBusModuleService_?.emit(groupedEvents[group]))
promises.push(this.eventBusModuleService_.emit(groupedEvents[group]))
}
await Promise.all(promises)
@@ -1,7 +1,8 @@
import { MessageAggregator } from "../../event-bus"
import { InjectIntoContext } from "./inject-into-context"
import {MessageAggregatorFormat} from "@medusajs/types";
export function EmitEvents() {
export function EmitEvents(options: MessageAggregatorFormat = {} as MessageAggregatorFormat) {
return function (
target: any,
propertyKey: string | symbol,
@@ -17,7 +18,7 @@ export function EmitEvents() {
descriptor.value = async function (...args: any[]) {
const result = await original.apply(this, args)
await target.emitEvents_.apply(this, [aggregator.getMessages()])
await target.emitEvents_.apply(this, [aggregator.getMessages(options)])
aggregator.clearMessages()
return result