1 /**
2 * Utility factory and interfaces for module service public facing API
3 */
4 import {
5 Context,
6 FindConfig,
7 IEventBusModuleService,
8 ModuleJoinerConfig,
9 RepositoryService,
10 RestoreReturn,
11 SoftDeleteReturn,
12 } from "@medusajs/types"
13 import { EventArgs } from "@mikro-orm/core"
14 import {
15 camelToSnakeCase,
16 lowerCaseFirst,
17 mapObjectTo,
18 MapToConfig,
19 pluralize,
20 upperCaseFirst,
21 } from "../common"
22 import { DmlEntity } from "../dml"
23 import { CommonEvents } from "../event-bus"
24 import { createMedusaMikroOrmEventSubscriber } from "./create-medusa-mikro-orm-event-subscriber"
25 import { EmitEvents, InjectManager, MedusaContext } from "./decorators"
26 import { Modules } from "./definition"
27 import { moduleEventBuilderFactory } from "./event-builder-factory"
28 import { buildModelsNameToLinkableKeysMap } from "./joiner-config-builder"
29 import { isMedusaInternalService } from "./medusa-internal-service"
30 import {
31 BaseMethods,
32 ExtractKeysFromConfig,
33 MedusaServiceReturnType,
34 ModelConfigurationsToConfigTemplate,
35 ModelEntries,
36 ModelsConfigTemplate,
37 } from "./types/medusa-service"
38
39 const readMethods = ["retrieve", "list", "listAndCount"] as BaseMethods[]
40 const writeMethods = [
41 "delete",
42 "softDelete",
43 "restore",
44 "create",
45 "update",
46 ] as BaseMethods[]
47
48 const methods: BaseMethods[] = [...readMethods, ...writeMethods]
49
50 /**
51 * @internal
52 */
53 function buildMethodNamesFromModel(
54 defaultMethodName: string,
55 model: ModelEntries[keyof ModelEntries]
56 ): Record<string, string> {
57 return methods.reduce((acc, method) => {
58 let normalizedModelName: string = ""
59
60 if (method === "retrieve") {
61 normalizedModelName =
62 model && "singular" in model && model.singular
63 ? model.singular
64 : defaultMethodName
65 } else {
66 normalizedModelName =
67 model && "plural" in model && model.plural
68 ? model.plural
69 : pluralize(defaultMethodName)
70 }
71
72 const methodName = `${method}${upperCaseFirst(normalizedModelName)}`
73
74 return { ...acc, [method]: methodName }
75 }, {})
76 }
77
78 /**
79 * Accessible from the MedusaService, holds the model objects when provided
80 */
81 export const MedusaServiceModelObjectsSymbol = Symbol.for(
82 "MedusaServiceModelObjectsSymbol"
83 )
84
85 /**
86 * Symbol to mark a class as a Medusa service
87 */
88 export const MedusaServiceSymbol = Symbol.for("MedusaServiceSymbol")
89
90 /**
91 * Accessible from the MedusaService, holds the model name to linkable keys map
92 * to be used for softDelete and restore methods
93 */
94 export const MedusaServiceModelNameToLinkableKeysMapSymbol = Symbol.for(
95 "MedusaServiceModelNameToLinkableKeysMapSymbol"
96 )
97
98 /**
99 * Check if a value is a Medusa service
100 * @param value
101 */
102 export function isMedusaService(
103 value: any
104 ): value is MedusaServiceReturnType<any> {
105 return value && value?.prototype[MedusaServiceSymbol]
106 }
107
108 /**
109 * Factory function for creating an abstract module service
110 *
111 * @example
112 *
113 * // Here the DTO's and names will be inferred from the arguments
114 *
115 * const models = {
116 * Currency,
117 * Price,
118 * PriceList,
119 * PriceListRule,
120 * PriceListRuleValue,
121 * PriceRule,
122 * PriceSetRuleType,
123 * RuleType,
124 * }
125 *
126 * class MyService extends ModulesSdkUtils.MedusaService(models) {}
127 *
128 * @param models
129 */
130 export function MedusaService<
131 const ModelsConfig extends ModelsConfigTemplate = { __empty: any },
132 const TModels extends ModelEntries<
133 ExtractKeysFromConfig<ModelsConfig>
134 > = ModelEntries<ExtractKeysFromConfig<ModelsConfig>>
135 >(
136 models: TModels
137 ): MedusaServiceReturnType<
138 ModelsConfig extends { __empty: any }
139 ? ModelConfigurationsToConfigTemplate<TModels>
140 : ModelsConfig
141 > {
142 const buildAndAssignMethodImpl = function (
143 klassPrototype: any,
144 method: string,
145 methodName: string,
146 modelName: string
147 ): void {
148 const serviceRegistrationName = `${lowerCaseFirst(modelName)}Service`
149
150 const applyMethod = function (impl: Function, contextIndex) {
151 klassPrototype[methodName] = impl
152
153 const descriptorMockRef = {
154 value: klassPrototype[methodName],
155 }
156
157 // The order of the decorators is important, do not change it
158 MedusaContext()(klassPrototype, methodName, contextIndex)
159 EmitEvents()(klassPrototype, methodName, descriptorMockRef)
160 InjectManager()(klassPrototype, methodName, descriptorMockRef)
161
162 klassPrototype[methodName] = descriptorMockRef.value
163 }
164
165 let methodImplementation: any = function () {
166 void 0
167 }
168
169 switch (method) {
170 case "retrieve":
171 methodImplementation = async function <T extends object>(
172 this: AbstractModuleService_,
173 id: string,
174 config?: FindConfig<any>,
175 sharedContext: Context = {}
176 ): Promise<T> {
177 const models = await this.__container__[
178 serviceRegistrationName
179 ].retrieve(id, config, sharedContext)
180
181 return await this.baseRepository_.serialize<T>(models)
182 }
183
184 applyMethod(methodImplementation, 2)
185
186 break
187 case "create":
188 methodImplementation = async function <T extends object>(
189 this: AbstractModuleService_,
190 data = [],
191 sharedContext: Context = {}
192 ): Promise<T | T[]> {
193 const service = this.__container__[serviceRegistrationName]
194 const models_ = await service.create(data, sharedContext)
195
196 return await this.baseRepository_.serialize<T | T[]>(models_)
197 }
198
199 applyMethod(methodImplementation, 1)
200
201 break
202 case "update":
203 methodImplementation = async function <T extends object>(
204 this: AbstractModuleService_,
205 data = [],
206 sharedContext: Context = {}
207 ): Promise<T | T[]> {
208 const service = this.__container__[serviceRegistrationName]
209 const response = await service.update(data, sharedContext)
210
211 return await this.baseRepository_.serialize<T | T[]>(response)
212 }
213
214 applyMethod(methodImplementation, 1)
215
216 break
217 case "list":
218 methodImplementation = async function <T extends object>(
219 this: AbstractModuleService_,
220 filters = {},
221 config: FindConfig<any> = {},
222 sharedContext: Context = {}
223 ): Promise<T[]> {
224 const service = this.__container__[serviceRegistrationName]
225 const models = await service.list(filters, config, sharedContext)
226
227 return await this.baseRepository_.serialize<T[]>(models)
228 }
229
230 applyMethod(methodImplementation, 2)
231
232 break
233 case "listAndCount":
234 methodImplementation = async function <T extends object>(
235 this: AbstractModuleService_,
236 filters = {},
237 config: FindConfig<any> = {},
238 sharedContext: Context = {}
239 ): Promise<T[]> {
240 const [models, count] = await this.__container__[
241 serviceRegistrationName
242 ].listAndCount(filters, config, sharedContext)
243
244 return [await this.baseRepository_.serialize<T[]>(models), count]
245 }
246
247 applyMethod(methodImplementation, 2)
248
249 break
250 case "delete":
251 methodImplementation = async function (
252 this: AbstractModuleService_,
253 primaryKeyValues: string | object | string[] | object[],
254 sharedContext: Context = {}
255 ): Promise<void> {
256 const primaryKeyValues_ = Array.isArray(primaryKeyValues)
257 ? primaryKeyValues
258 : [primaryKeyValues]
259
260 await this.__container__[serviceRegistrationName].delete(
261 primaryKeyValues_,
262 sharedContext
263 )
264 }
265
266 applyMethod(methodImplementation, 1)
267
268 break
269 case "softDelete":
270 methodImplementation = async function <T extends { id: string }>(
271 this: AbstractModuleService_,
272 primaryKeyValues: string | object | string[] | object[],
273 config: SoftDeleteReturn<string> = {},
274 sharedContext: Context = {}
275 ): Promise<Record<string, string[]> | void> {
276 const primaryKeyValues_ = Array.isArray(primaryKeyValues)
277 ? primaryKeyValues
278 : [primaryKeyValues]
279
280 const [, cascadedModelsMap] = await this.__container__[
281 serviceRegistrationName
282 ].softDelete(primaryKeyValues_, sharedContext)
283
284 // Map internal table/column names to their respective external linkable keys
285 // eg: product.id = product_id, variant.id = variant_id
286 const mappedCascadedModelsMap = mapObjectTo(
287 cascadedModelsMap,
288 this[MedusaServiceModelNameToLinkableKeysMapSymbol],
289 {
290 pick: config.returnLinkableKeys,
291 }
292 )
293
294 return mappedCascadedModelsMap ? mappedCascadedModelsMap : void 0
295 }
296
297 applyMethod(methodImplementation, 2)
298
299 break
300 case "restore":
301 methodImplementation = async function <T extends object>(
302 this: AbstractModuleService_,
303 primaryKeyValues: string | object | string[] | object[],
304 config: RestoreReturn<string> = {},
305 sharedContext: Context = {}
306 ): Promise<Record<string, string[]> | void> {
307 const primaryKeyValues_ = Array.isArray(primaryKeyValues)
308 ? primaryKeyValues
309 : [primaryKeyValues]
310
311 const [, cascadedModelsMap] = await this.__container__[
312 serviceRegistrationName
313 ].restore(primaryKeyValues_, sharedContext)
314
315 let mappedCascadedModelsMap
316 // Map internal table/column names to their respective external linkable keys
317 // eg: product.id = product_id, variant.id = variant_id
318 mappedCascadedModelsMap = mapObjectTo(
319 cascadedModelsMap,
320 this[MedusaServiceModelNameToLinkableKeysMapSymbol],
321 {
322 pick: config.returnLinkableKeys,
323 }
324 )
325
326 return mappedCascadedModelsMap ? mappedCascadedModelsMap : void 0
327 }
328
329 applyMethod(methodImplementation, 2)
330
331 break
332 }
333 }
334
335 class AbstractModuleService_ {
336 [MedusaServiceSymbol] = true
337
338 static [MedusaServiceModelObjectsSymbol] =
339 models as unknown as MedusaServiceReturnType<
340 ModelsConfig extends { __empty: any }
341 ? ModelConfigurationsToConfigTemplate<TModels>
342 : ModelsConfig
343 >["$modelObjects"];
344
345 [MedusaServiceModelNameToLinkableKeysMapSymbol]: MapToConfig
346
347 readonly __container__: Record<any, any>
348 readonly baseRepository_: RepositoryService
349 readonly eventBusModuleService_: IEventBusModuleService
350
351 __joinerConfig?(): ModuleJoinerConfig
352
353 constructor(container: Record<any, any>) {
354 this.__container__ = container
355 this.baseRepository_ = container.baseRepository
356
357 const joinerConfig = this.__joinerConfig?.()
358 /**
359 * Create a global subscriber to listen to all the entities mutations
360 * and forward them to the module service interceptEntityMutationEvents
361 * method.
362 *
363 * Assign the global subscriber to all internal services or class that extends it
364 * such that it can attach it accordingly and forward the events to the module service.
365 */
366
367 if (joinerConfig?.serviceName !== "index") {
368 let globalSubscriber!: ReturnType<
369 typeof createMedusaMikroOrmEventSubscriber
370 >
371
372 Object.keys(container)
373 .filter((key) => {
374 return key.endsWith("Service")
375 })
376 .forEach((key: string) => {
377 globalSubscriber ??= createMedusaMikroOrmEventSubscriber(
378 ["__medusa_entities_subscriber__"],
379 this
380 )
381 try {
382 const service = container[key]
383 if (isMedusaInternalService(service)) {
384 service.setEventSubscriber(globalSubscriber)
385 }
386 } catch (error) {
387 // Prevent circular issue which in that case would represent ourselves so we can skip
388 }
389 })
390 }
391
392 const hasEventBusModuleService = Object.keys(this.__container__).find(
393 (key) => key === Modules.EVENT_BUS
394 )
395
396 this.eventBusModuleService_ = hasEventBusModuleService
397 ? this.__container__[Modules.EVENT_BUS]
398 : undefined
399
400 this[MedusaServiceModelNameToLinkableKeysMapSymbol] =
401 buildModelsNameToLinkableKeysMap(joinerConfig?.linkableKeys ?? {})
402 }
403
404 /**
405 * @internal this method is meant to react to any event the orm might emit
406 * when an entity is being mutated (created, updated, deleted).
407 * The default implementation will handle all event to be emitted as part
408 * of the message aggregator from the context.
409 *
410 * If you want to handle the event differently, you can override this method.
411 *
412 * @example
413 *
414 * class MyService extends ModulesSdkUtils.MedusaService(models) {
415 * interceptEntityMutationEvents(event: "afterCreate" | "afterUpdate" | "afterUpsert" | "afterDelete", args: EventArgs<any>, context: Context) {
416 * console.log("interceptEntityMutationEvents", event, args.entity)
417 * }
418 * }
419 *
420 * @param event - The event type
421 * @param args - The event arguments
422 * @param context - The context
423 */
424 interceptEntityMutationEvents(
425 event: "afterCreate" | "afterUpdate" | "afterUpsert" | "afterDelete",
426 args: EventArgs<any>,
427 context: Context
428 ) {
429 let action = ""
430 switch (event) {
431 case "afterCreate":
432 action = CommonEvents.CREATED
433 break
434 case "afterUpdate":
435 const isSoftDeleted =
436 !!args.changeSet?.entity.deleted_at &&
437 !args.changeSet?.originalEntity?.deleted_at
438
439 const isRestored =
440 !!args.changeSet?.originalEntity?.deleted_at &&
441 !args.changeSet?.entity.deleted_at
442
443 action = CommonEvents.UPDATED
444
445 if (isSoftDeleted) {
446 action = CommonEvents.DELETED
447 }
448
449 if (isRestored) {
450 action = CommonEvents.RESTORED
451 }
452
453 break
454 case "afterDelete":
455 action = CommonEvents.DELETED
456 break
457 }
458
459 const object = camelToSnakeCase(args.meta.className).toLowerCase()
460
461 // Resolve the identifier from the model's real primary key rather than
462 // assuming an `id` column, so models with a custom (non-id) primary key
463 // still emit the correct identifier. `args.meta.primaryKeys` is provided
464 // by MikroORM for native events and forwarded manually for the events we
465 // dispatch ourselves (e.g. delete, upsert with replace).
466 const primaryKey = args.meta.primaryKeys?.[0] ?? "id"
467
468 this.aggregatedEvents({
469 action,
470 object,
471 data: { id: args.entity[primaryKey] ?? args.entity.id },
472 context,
473 })
474 }
475
476 /**
477 * helper function to aggregate events. Will format the message properly and store in
478 * the message aggregator from the context. The method must be decorated with `@EmitEvents`
479 * @param action
480 * @param object
481 * @param eventName optional, can be inferred from the module joiner config + action + object
482 * @param source optional, can be inferred from the module joiner config
483 * @param data
484 * @param context
485 */
486 protected aggregatedEvents({
487 action,
488 object,
489 eventName,
490 source,
491 data,
492 context,
493 }: {
494 action: string
495 object: string
496 eventName?: string
497 source?: string
498 data: { id: any } | { id: any }[]
499 context: Context
500 }) {
501 if (!context.messageAggregator) {
502 return
503 }
504
505 const __joinerConfig = (
506 typeof this.__joinerConfig === "function"
507 ? this.__joinerConfig()
508 : this.__joinerConfig
509 ) as ModuleJoinerConfig
510
511 const eventBuilder = moduleEventBuilderFactory({
512 action,
513 object,
514 source: source || __joinerConfig.serviceName!,
515 eventName,
516 })
517
518 eventBuilder({
519 data,
520 sharedContext: context,
521 })
522 }
523
524 /**
525 * @internal this method is not meant to be used except by the internal team for now
526 * @param groupedEvents
527 * @protected
528 */
529 protected async emitEvents_(groupedEvents) {
530 if (!this.eventBusModuleService_ || !groupedEvents) {
531 return
532 }
533
534 const promises: Promise<void>[] = []
535 for (const group of Object.keys(groupedEvents)) {
536 promises.push(
537 this.eventBusModuleService_.emit(groupedEvents[group], {
538 internal: true,
539 })
540 )
541 }
542
543 await Promise.all(promises)
544 }
545 }
546
547 /**
548 * Build the retrieve/list/listAndCount/delete/softDelete/restore methods for all the other models
549 */
550
551 const modelsMethods: [
552 string, // model name
553 TModels[keyof TModels], // configuration (dml, conf, entity)
554 Record<string, string> // method names
555 ][] = Object.entries(models as {}).map(([name, config]) => [
556 DmlEntity.isDmlEntity(config) ? config.name : name,
557 config as TModels[keyof TModels],
558 buildMethodNamesFromModel(name, config as TModels[keyof TModels]),
559 ])
560
561 for (let [modelName, , modelMethods] of modelsMethods) {
562 Object.entries(modelMethods).forEach(([method, methodName]) => {
563 buildAndAssignMethodImpl(
564 AbstractModuleService_.prototype,
565 method,
566 methodName,
567 modelName
568 )
569 })
570 }
571
572 return AbstractModuleService_ as any
573 }