1 import {
2 BaseFilterable,
3 Context,
4 FilterQuery,
5 FindConfig,
6 InferEntityType,
7 FilterQuery as InternalFilterQuery,
8 ModulesSdkTypes,
9 PerformedActions,
10 UpsertWithReplaceConfig,
11 } from "@medusajs/types"
12 import {
13 EventType,
14 type EntityClass,
15 type EntityManager,
16 type EntitySchema,
17 } from "@medusajs/deps/mikro-orm/core"
18 import {
19 isDefined,
20 isObject,
21 isPresent,
22 isString,
23 lowerCaseFirst,
24 MedusaError,
25 mergeMetadata,
26 } from "../common"
27 import { FreeTextSearchFilterKeyPrefix } from "../dal"
28 import { DmlEntity, toMikroORMEntity } from "../dml"
29 import { buildQuery } from "./build-query"
30 import {
31 InjectManager,
32 InjectTransactionManager,
33 MedusaContext,
34 } from "./decorators"
35 import { MedusaMikroOrmEventSubscriber } from "./create-medusa-mikro-orm-event-subscriber"
36
37 type InternalService = {
38 new <TContainer extends object = object, TEntity extends object = any>(
39 container: TContainer
40 ): ModulesSdkTypes.IMedusaInternalService<TEntity, TContainer>
41
42 setEventSubscriber(subscriber: MedusaMikroOrmEventSubscriber): void
43 }
44
45 type SelectorAndData = {
46 selector: FilterQuery<any> | BaseFilterable<FilterQuery<any>>
47 data: any
48 }
49
50 export function registerInternalServiceEventSubscriber(
51 context: Context,
52 subscriber?: MedusaMikroOrmEventSubscriber
53 ) {
54 const manager = (context.transactionManager ??
55 context.manager) as EntityManager
56 if (manager && subscriber) {
57 const subscriberInstance = new subscriber(context)
58 const hasListeners = Array.from(
59 manager.getEventManager().getSubscribers()
60 ).some((s) => s.constructor.name === subscriberInstance.constructor.name)
61 if (!hasListeners) {
62 manager.getEventManager().registerSubscriber(subscriberInstance)
63 }
64 }
65 }
66
67 export const MedusaInternalServiceSymbol = Symbol.for(
68 "MedusaInternalServiceSymbol"
69 )
70
71 /**
72 * Check if a value is a Medusa internal service
73 * @param value
74 */
75 export function isMedusaInternalService(value: any): value is InternalService {
76 return (
77 !!value?.[MedusaInternalServiceSymbol] ||
78 !!value?.prototype?.[MedusaInternalServiceSymbol]
79 )
80 }
81
82 export function MedusaInternalService<
83 TContainer extends object = object,
84 TEntity extends object = any
85 >(rawModel: any): InternalService {
86 const model = DmlEntity.isDmlEntity(rawModel)
87 ? toMikroORMEntity(rawModel)
88 : rawModel
89
90 const injectedRepositoryName = `${lowerCaseFirst(model.name)}Repository`
91 const propertyRepositoryName = `__${injectedRepositoryName}__`
92
93 class AbstractService_
94 implements ModulesSdkTypes.IMedusaInternalService<TEntity, TContainer>
95 {
96 [MedusaInternalServiceSymbol] = true
97
98 #eventSubscriber?: MedusaMikroOrmEventSubscriber
99
100 readonly __container__: TContainer;
101 [key: string]: any
102
103 constructor(container: TContainer) {
104 this.__container__ = container
105 this[propertyRepositoryName] = container[injectedRepositoryName]
106 }
107
108 setEventSubscriber(subscriber: MedusaMikroOrmEventSubscriber) {
109 this.#eventSubscriber = subscriber
110 }
111
112 static applyFreeTextSearchFilter(
113 filters: FilterQuery & { q?: string },
114 config: FindConfig<any>
115 ): void {
116 if (isDefined(filters?.q)) {
117 config.filters ??= {}
118 config.filters[FreeTextSearchFilterKeyPrefix + model.name] = {
119 value: filters.q,
120 fromEntity: model.name,
121 }
122 delete filters.q
123 }
124 }
125
126 static retrievePrimaryKeys(entity: EntityClass<any> | EntitySchema<any>) {
127 return (
128 (entity as EntitySchema<any>).meta?.primaryKeys ??
129 (entity as EntityClass<any>).prototype.__meta?.primaryKeys ?? ["id"]
130 )
131 }
132
133 static buildUniqueCompositeKeyValue(keys: string[], data: object) {
134 return keys.map((k) => data[k]).join(":")
135 }
136
137 /**
138 * Only apply top level default ordering as the relation
139 * default ordering is already applied through the foreign key
140 * @param config
141 */
142 static applyDefaultOrdering(config: FindConfig<any>) {
143 if (isPresent(config.order)) {
144 return
145 }
146
147 config.order = {}
148
149 const primaryKeys = AbstractService_.retrievePrimaryKeys(model)
150 primaryKeys.forEach((primaryKey) => {
151 config.order![primaryKey] = "ASC"
152 })
153 }
154
155 @InjectManager(propertyRepositoryName)
156 async retrieve(
157 idOrObject: string | object,
158 config: FindConfig<InferEntityType<TEntity>> = {},
159 @MedusaContext() sharedContext: Context = {}
160 ): Promise<InferEntityType<TEntity>> {
161 const primaryKeys = AbstractService_.retrievePrimaryKeys(model)
162
163 if (
164 !isDefined(idOrObject) ||
165 (isString(idOrObject) && primaryKeys.length > 1) ||
166 ((!isString(idOrObject) ||
167 (isObject(idOrObject) && !idOrObject[primaryKeys[0]])) &&
168 primaryKeys.length === 1)
169 ) {
170 throw new MedusaError(
171 MedusaError.Types.NOT_FOUND,
172 `${
173 primaryKeys.length === 1
174 ? `${lowerCaseFirst(model.name) + " - " + primaryKeys[0]}`
175 : `${lowerCaseFirst(model.name)} - ${primaryKeys.join(", ")}`
176 } must be defined`
177 )
178 }
179
180 let primaryKeysCriteria = {}
181 if (primaryKeys.length === 1) {
182 primaryKeysCriteria[primaryKeys[0]] = idOrObject
183 } else {
184 const idOrObject_ = Array.isArray(idOrObject)
185 ? idOrObject
186 : [idOrObject]
187 primaryKeysCriteria = {
188 $or: idOrObject_.map((primaryKeyValue) => ({
189 $and: primaryKeys.map((key) => ({ [key]: primaryKeyValue[key] })),
190 })),
191 }
192 }
193
194 const queryOptions = buildQuery(primaryKeysCriteria, config)
195
196 const entities = await this[propertyRepositoryName].find(
197 queryOptions,
198 sharedContext
199 )
200
201 if (!entities?.length) {
202 throw new MedusaError(
203 MedusaError.Types.NOT_FOUND,
204 `${model.name} with ${primaryKeys.join(", ")}: ${
205 Array.isArray(idOrObject)
206 ? idOrObject.map((v) =>
207 [isString(v) ? v : Object.values(v)].join(", ")
208 )
209 : isObject(idOrObject)
210 ? Object.values(idOrObject).join(", ")
211 : idOrObject
212 } was not found`
213 )
214 }
215
216 return entities[0]
217 }
218
219 @InjectManager(propertyRepositoryName)
220 async list(
221 filters: FilterQuery<any> | BaseFilterable<FilterQuery<any>> = {},
222 config: FindConfig<any> = {},
223 @MedusaContext() sharedContext: Context = {}
224 ): Promise<InferEntityType<TEntity>[]> {
225 AbstractService_.applyDefaultOrdering(config)
226 AbstractService_.applyFreeTextSearchFilter(filters, config)
227
228 const queryOptions = buildQuery(filters, config)
229
230 return await this[propertyRepositoryName].find(
231 queryOptions,
232 sharedContext
233 )
234 }
235
236 @InjectManager(propertyRepositoryName)
237 async listAndCount(
238 filters: FilterQuery<any> | BaseFilterable<FilterQuery<any>> = {},
239 config: FindConfig<any> = {},
240 @MedusaContext() sharedContext: Context = {}
241 ): Promise<[InferEntityType<TEntity>[], number]> {
242 AbstractService_.applyDefaultOrdering(config)
243 AbstractService_.applyFreeTextSearchFilter(filters, config)
244
245 const queryOptions = buildQuery(filters, config)
246
247 return await this[propertyRepositoryName].findAndCount(
248 queryOptions,
249 sharedContext
250 )
251 }
252
253 create(
254 data: any,
255 sharedContext?: Context
256 ): Promise<InferEntityType<TEntity>>
257 create(
258 data: any[],
259 sharedContext?: Context
260 ): Promise<InferEntityType<TEntity>[]>
261
262 @InjectTransactionManager(propertyRepositoryName)
263 async create(
264 data: any | any[],
265 @MedusaContext() sharedContext: Context = {}
266 ): Promise<InferEntityType<TEntity> | InferEntityType<TEntity>[]> {
267 if (!isDefined(data) || (Array.isArray(data) && data.length === 0)) {
268 return (Array.isArray(data) ? [] : void 0) as
269 | InferEntityType<TEntity>
270 | InferEntityType<TEntity>[]
271 }
272
273 registerInternalServiceEventSubscriber(
274 sharedContext,
275 this.#eventSubscriber
276 )
277
278 const data_ = Array.isArray(data) ? data : [data]
279 const entities = await this[propertyRepositoryName].create(
280 data_,
281 sharedContext
282 )
283
284 return Array.isArray(data) ? entities : entities[0]
285 }
286
287 update(
288 data: any[],
289 sharedContext?: Context
290 ): Promise<InferEntityType<TEntity>[]>
291 update(
292 data: any,
293 sharedContext?: Context
294 ): Promise<InferEntityType<TEntity>>
295 update(
296 selectorAndData: SelectorAndData,
297 sharedContext?: Context
298 ): Promise<InferEntityType<TEntity>[]>
299 update(
300 selectorAndData: SelectorAndData[],
301 sharedContext?: Context
302 ): Promise<InferEntityType<TEntity>[]>
303
304 @InjectTransactionManager(propertyRepositoryName)
305 async update(
306 input: any | any[] | SelectorAndData | SelectorAndData[],
307 @MedusaContext() sharedContext: Context = {}
308 ): Promise<InferEntityType<TEntity> | InferEntityType<TEntity>[]> {
309 if (!isDefined(input) || (Array.isArray(input) && input.length === 0)) {
310 return (Array.isArray(input) ? [] : void 0) as
311 | InferEntityType<TEntity>
312 | InferEntityType<TEntity>[]
313 }
314
315 registerInternalServiceEventSubscriber(
316 sharedContext,
317 this.#eventSubscriber
318 )
319
320 let shouldReturnArray = false
321 if (Array.isArray(input)) {
322 shouldReturnArray = true
323 } else if (isObject(input) && "selector" in input) {
324 shouldReturnArray = true
325 }
326
327 const primaryKeys = AbstractService_.retrievePrimaryKeys(model)
328 const inputArray = Array.isArray(input) ? input : [input]
329
330 const toUpdateData: { entity: TEntity; update: Partial<TEntity> }[] = []
331
332 // Only used when we receive data and no selector
333 const keySelectorForDataOnly: any = {
334 $or: [],
335 }
336 const keySelectorDataMap = new Map<string, any>()
337
338 for (const input_ of inputArray) {
339 if (input_.selector) {
340 const entitiesToUpdate = await this.list(
341 input_.selector,
342 {},
343 sharedContext
344 )
345
346 // Create a pair of entity and data to update
347 entitiesToUpdate.forEach((entity) => {
348 toUpdateData.push({
349 entity,
350 update: input_.data,
351 })
352 })
353 } else {
354 // in case we are manipulating the data, then extract the primary keys as a selector and the rest as the data to update
355 const selector = {}
356
357 primaryKeys.forEach((key) => {
358 selector[key] = input_[key]
359 })
360
361 const uniqueCompositeKey =
362 AbstractService_.buildUniqueCompositeKeyValue(primaryKeys, input_)
363 keySelectorDataMap.set(uniqueCompositeKey, input_)
364
365 keySelectorForDataOnly.$or.push(selector)
366 }
367 }
368
369 if (keySelectorForDataOnly.$or.length) {
370 const entitiesToUpdate = await this.list(
371 keySelectorForDataOnly,
372 {},
373 sharedContext
374 )
375
376 // Create a pair of entity and data to update
377 entitiesToUpdate.forEach((entity) => {
378 const uniqueCompositeKey =
379 AbstractService_.buildUniqueCompositeKeyValue(primaryKeys, entity)
380 toUpdateData.push({
381 entity,
382 update: keySelectorDataMap.get(uniqueCompositeKey)!,
383 })
384 })
385
386 // Only throw for missing entities when we dont have selectors involved as selector by design can return 0 entities
387 if (entitiesToUpdate.length !== keySelectorDataMap.size) {
388 const entityName =
389 (model as EntityClass<InferEntityType<TEntity>>).name ?? model
390
391 const compositeKeysValuesForFoundEntities = new Set(
392 entitiesToUpdate.map((entity) => {
393 return AbstractService_.buildUniqueCompositeKeyValue(
394 primaryKeys,
395 entity
396 )
397 })
398 )
399
400 const missingEntityValues: any[] = []
401
402 ;[...keySelectorDataMap.keys()].filter((key) => {
403 if (!compositeKeysValuesForFoundEntities.has(key)) {
404 const value = key.replace(/:/gi, " - ")
405 missingEntityValues.push(value)
406 }
407 })
408
409 throw new MedusaError(
410 MedusaError.Types.NOT_FOUND,
411 `${entityName} with ${primaryKeys.join(
412 ", "
413 )} "${missingEntityValues.join(", ")}" not found`
414 )
415 }
416 }
417
418 if (!toUpdateData.length) {
419 return (shouldReturnArray ? [] : void 0) as
420 | InferEntityType<TEntity>
421 | InferEntityType<TEntity>[]
422 }
423
424 // Manage metadata if needed
425 toUpdateData.forEach(({ entity, update }) => {
426 const update_ = update as (typeof toUpdateData)[number]["update"] & {
427 metadata: Record<string, unknown>
428 }
429 const entity_ = entity as InferEntityType<TEntity> & {
430 metadata?: Record<string, unknown>
431 }
432
433 if (isPresent(update_.metadata)) {
434 entity_.metadata = update_.metadata = mergeMetadata(
435 entity_.metadata ?? {},
436 update_.metadata
437 )
438 }
439 })
440
441 const entities = await this[propertyRepositoryName].update(
442 toUpdateData,
443 sharedContext
444 )
445
446 return shouldReturnArray ? entities : entities[0]
447 }
448
449 delete(
450 idOrSelector: string,
451 sharedContext?: Context
452 ): Promise<string[] | Record<string, any>[]>
453 delete(
454 idOrSelector: string[],
455 sharedContext?: Context
456 ): Promise<string[] | Record<string, any>[]>
457 delete(
458 idOrSelector: object,
459 sharedContext?: Context
460 ): Promise<string[] | Record<string, any>[]>
461 delete(
462 idOrSelector: object[],
463 sharedContext?: Context
464 ): Promise<string[] | Record<string, any>[]>
465 delete(
466 idOrSelector: {
467 selector: FilterQuery<any> | BaseFilterable<FilterQuery<any>>
468 },
469 sharedContext?: Context
470 ): Promise<string[] | Record<string, any>[]>
471
472 @InjectTransactionManager(propertyRepositoryName)
473 async delete(
474 idOrSelector:
475 | string
476 | string[]
477 | object
478 | object[]
479 | {
480 selector: FilterQuery<any> | BaseFilterable<FilterQuery<any>>
481 },
482 @MedusaContext() sharedContext: Context = {}
483 ): Promise<string[] | Record<string, any>[]> {
484 if (
485 !isDefined(idOrSelector) ||
486 (Array.isArray(idOrSelector) && !idOrSelector.length)
487 ) {
488 return []
489 }
490
491 registerInternalServiceEventSubscriber(
492 sharedContext,
493 this.#eventSubscriber
494 )
495
496 const primaryKeys = AbstractService_.retrievePrimaryKeys(model)
497
498 if (
499 (Array.isArray(idOrSelector) && idOrSelector.length === 0) ||
500 ((isString(idOrSelector) ||
501 (Array.isArray(idOrSelector) && isString(idOrSelector[0]))) &&
502 primaryKeys.length > 1)
503 ) {
504 throw new MedusaError(
505 MedusaError.Types.NOT_FOUND,
506 `${
507 primaryKeys.length === 1
508 ? `"${lowerCaseFirst(model.name) + " - " + primaryKeys[0]}"`
509 : `${lowerCaseFirst(model.name)} - ${primaryKeys.join(", ")}`
510 } must be defined`
511 )
512 }
513
514 const deleteCriteria: any = {
515 $or: [],
516 }
517
518 if (isObject(idOrSelector) && "selector" in idOrSelector) {
519 deleteCriteria.$or.push(idOrSelector.selector)
520 } else {
521 const primaryKeysValues = Array.isArray(idOrSelector)
522 ? idOrSelector
523 : [idOrSelector]
524
525 deleteCriteria.$or = primaryKeysValues.map((primaryKeyValue) => {
526 const criteria = {}
527
528 if (isObject(primaryKeyValue)) {
529 Object.entries(primaryKeyValue).forEach(([key, value]) => {
530 criteria[key] = value
531 })
532 } else {
533 criteria[primaryKeys[0]] = primaryKeyValue
534 }
535
536 return criteria
537 })
538 }
539
540 if (!deleteCriteria.$or.length) {
541 return []
542 }
543
544 const deletedIds = await this[propertyRepositoryName].delete(
545 deleteCriteria,
546 sharedContext
547 )
548
549 // Delete are handled a bit differently since we are going to the DB directly, therefore
550 // just like upsert with replace, we need to dispatch the events manually.
551 if (deletedIds.length) {
552 const manager = (sharedContext.transactionManager ??
553 sharedContext.manager) as EntityManager
554 const eventManager = manager.getEventManager()
555
556 deletedIds.forEach((deletedId) => {
557 // `delete` returns a flat primary key value for single primary keys
558 // and an object keyed by the primary key property names for composite
559 // keys. Build the event payload using the model's real primary key(s)
560 // rather than a hardcoded `id`, so models with a custom (non-id) or
561 // composite primary key emit the correct identifier.
562 const entity = isObject(deletedId)
563 ? deletedId
564 : { [primaryKeys[0]]: deletedId }
565
566 eventManager.dispatchEvent(EventType.afterDelete, {
567 entity,
568 meta: {
569 className: model.name,
570 primaryKeys,
571 } as Parameters<typeof eventManager.dispatchEvent>[2],
572 })
573 })
574 }
575
576 return deletedIds
577 }
578
579 @InjectTransactionManager(propertyRepositoryName)
580 async softDelete(
581 idsOrFilter:
582 | string
583 | string[]
584 | InternalFilterQuery
585 | InternalFilterQuery[],
586 @MedusaContext() sharedContext: Context = {}
587 ): Promise<[InferEntityType<TEntity>[], Record<string, unknown[]>]> {
588 if (
589 (Array.isArray(idsOrFilter) && !idsOrFilter.length) ||
590 (!Array.isArray(idsOrFilter) && !idsOrFilter)
591 ) {
592 return [[], {}]
593 }
594
595 registerInternalServiceEventSubscriber(
596 sharedContext,
597 this.#eventSubscriber
598 )
599
600 return await this[propertyRepositoryName].softDelete(
601 idsOrFilter,
602 sharedContext
603 )
604 }
605
606 @InjectTransactionManager(propertyRepositoryName)
607 async restore(
608 idsOrFilter: string[] | InternalFilterQuery,
609 @MedusaContext() sharedContext: Context = {}
610 ): Promise<[InferEntityType<TEntity>[], Record<string, unknown[]>]> {
611 return await this[propertyRepositoryName].restore(
612 idsOrFilter,
613 sharedContext
614 )
615 }
616
617 upsert(
618 data: any[],
619 sharedContext?: Context
620 ): Promise<InferEntityType<TEntity>[]>
621 upsert(
622 data: any,
623 sharedContext?: Context
624 ): Promise<InferEntityType<TEntity>>
625
626 @InjectTransactionManager(propertyRepositoryName)
627 async upsert(
628 data: any | any[],
629 @MedusaContext() sharedContext: Context = {}
630 ): Promise<InferEntityType<TEntity> | InferEntityType<TEntity>[]> {
631 registerInternalServiceEventSubscriber(
632 sharedContext,
633 this.#eventSubscriber
634 )
635
636 const data_ = Array.isArray(data) ? data : [data]
637 const entities = await this[propertyRepositoryName].upsert(
638 data_,
639 sharedContext
640 )
641 return Array.isArray(data) ? entities : entities[0]
642 }
643
644 upsertWithReplace(
645 data: any[],
646 config?: UpsertWithReplaceConfig<InferEntityType<TEntity>>,
647 sharedContext?: Context
648 ): Promise<{
649 entities: InferEntityType<TEntity>[]
650 performedActions: PerformedActions
651 }>
652 upsertWithReplace(
653 data: any,
654 config?: UpsertWithReplaceConfig<InferEntityType<TEntity>>,
655 sharedContext?: Context
656 ): Promise<{
657 entities: InferEntityType<TEntity>
658 performedActions: PerformedActions
659 }>
660
661 @InjectTransactionManager(propertyRepositoryName)
662 async upsertWithReplace(
663 data: any | any[],
664 config: UpsertWithReplaceConfig<InferEntityType<TEntity>> = {
665 relations: [],
666 },
667 @MedusaContext() sharedContext: Context = {}
668 ): Promise<{
669 entities: InferEntityType<TEntity> | InferEntityType<TEntity>[]
670 performedActions: PerformedActions
671 }> {
672 registerInternalServiceEventSubscriber(
673 sharedContext,
674 this.#eventSubscriber
675 )
676
677 const data_ = Array.isArray(data) ? data : [data]
678 const { entities, performedActions } = await this[
679 propertyRepositoryName
680 ].upsertWithReplace(data_, config, sharedContext)
681
682 const manager = (sharedContext.transactionManager ??
683 sharedContext.manager) as EntityManager
684 const eventManager = manager.getEventManager()
685
686 /**
687 * Since the upsertWithReplace method is not emitting events, we need to do it manually
688 * by dispatching the events manually.
689 */
690
691 const createdEntities = !!Object.keys(performedActions.created).length
692 const updatedEntities = !!Object.keys(performedActions.updated).length
693 const deletedEntities = !!Object.keys(performedActions.deleted).length
694
695 if (createdEntities) {
696 Object.entries(
697 performedActions.created as Record<string, any[]>
698 ).forEach(([modelName, entities]) => {
699 entities.forEach((entity) => {
700 eventManager.dispatchEvent(EventType.afterCreate, {
701 entity,
702 meta: {
703 className: modelName,
704 } as Parameters<typeof eventManager.dispatchEvent>[2],
705 })
706 })
707 })
708 }
709
710 if (updatedEntities) {
711 Object.entries(
712 performedActions.updated as Record<string, any[]>
713 ).forEach(([modelName, entities]) => {
714 entities.forEach((entity) => {
715 eventManager.dispatchEvent(EventType.afterUpdate, {
716 entity,
717 meta: {
718 className: modelName,
719 } as Parameters<typeof eventManager.dispatchEvent>[2],
720 })
721 })
722 })
723 }
724
725 if (deletedEntities) {
726 Object.entries(
727 performedActions.deleted as Record<string, any[]>
728 ).forEach(([modelName, entities]) => {
729 entities.forEach((entity) => {
730 eventManager.dispatchEvent(EventType.afterDelete, {
731 entity,
732 meta: {
733 className: modelName,
734 } as Parameters<typeof eventManager.dispatchEvent>[2],
735 })
736 })
737 })
738 }
739
740 return {
741 entities: Array.isArray(data) ? entities : entities[0],
742 performedActions,
743 }
744 }
745 }
746
747 // We hide away the setEventSubscriber method from the public interface
748 // as it is not meant to be used by the user.
749 return AbstractService_ as unknown as InternalService
750 }