1 import {
2 Context,
3 ILinkModule,
4 LinkDefinition,
5 LoadedModule,
6 ModuleJoinerRelationship,
7 } from "@medusajs/types"
8
9 import {
10 isObject,
11 MedusaContext,
12 MedusaError,
13 MedusaModuleType,
14 Modules,
15 promiseAll,
16 toPascalCase,
17 } from "@medusajs/utils"
18 import { MedusaModule } from "./medusa-module"
19 import { convertRecordsToLinkDefinition } from "./utils/convert-data-to-link-definition"
20 import { linkingErrorMessage } from "./utils/linking-error"
21
22 /**
23 * The details of a data model's record whose linked records should be deleted. Usually used after the
24 * data model's record is deleted.
25 *
26 * The key is the data model's name. Its value is an object that has the ID of the data model's record.
27 */
28 export type DeleteEntityInput = {
29 [moduleName: string | Modules]: Record<string, string | string[]>
30 }
31 export type RestoreEntityInput = DeleteEntityInput
32
33 type RemoteRelationship = ModuleJoinerRelationship & {
34 isPrimary: boolean
35 isForeign: boolean
36 }
37
38 type LoadedLinkModule = LoadedModule & ILinkModule
39 type DeleteEntities = { [key: string]: string[] }
40 type RemovedIds = {
41 [serviceName: string]: DeleteEntities
42 }
43 type RestoredIds = RemovedIds
44
45 type CascadeError = {
46 serviceName: string
47 method: String
48 args: any
49 error: Error
50 }
51
52 type LinkDataConfig = {
53 moduleA: string
54 moduleB: string
55 primaryKeys: string[]
56 moduleAKey: string
57 moduleBKey: string
58 }
59
60 export class Link {
61 // To not lose the context chain, we need to set the type to MedusaModuleType
62 static __type = MedusaModuleType
63
64 private modulesMap: Map<string, LoadedLinkModule> = new Map()
65 private relationsPairs: Map<string, LoadedLinkModule> = new Map()
66 private relations: Map<string, Map<string, RemoteRelationship[]>> = new Map()
67
68 constructor(modulesLoaded?: LoadedModule[]) {
69 if (!modulesLoaded?.length) {
70 modulesLoaded = MedusaModule.getLoadedModules().map(
71 (mod) => Object.values(mod)[0]
72 )
73 }
74
75 for (const mod of modulesLoaded || []) {
76 this.addModule(mod)
77 }
78 }
79
80 public addModule(mod: LoadedModule): void {
81 if (!mod.__definition.isQueryable || mod.__joinerConfig.isReadOnlyLink) {
82 return
83 }
84
85 const joinerConfig = mod.__joinerConfig
86
87 const serviceName = joinerConfig.isLink
88 ? joinerConfig.serviceName!
89 : mod.__definition.key
90
91 if (this.modulesMap.has(serviceName)) {
92 throw new Error(
93 `Duplicated instance of module ${serviceName} is not allowed.`
94 )
95 }
96
97 if (joinerConfig.relationships?.length) {
98 if (joinerConfig.isLink) {
99 const [primary, foreign] = joinerConfig.relationships
100 const key = [
101 primary.serviceName,
102 primary.foreignKey,
103 foreign.serviceName,
104 foreign.foreignKey,
105 ].join("-")
106 this.relationsPairs.set(key, mod as unknown as LoadedLinkModule)
107 }
108 for (const relationship of joinerConfig.relationships) {
109 if (joinerConfig.isLink && !relationship.deleteCascade) {
110 continue
111 }
112
113 this.addRelationship(serviceName, {
114 ...relationship,
115 isPrimary: false,
116 isForeign: true,
117 })
118 }
119 }
120
121 if (joinerConfig.extends?.length) {
122 for (const service of joinerConfig.extends) {
123 const relationship = service.relationship
124 this.addRelationship(service.serviceName, {
125 ...relationship,
126 serviceName: serviceName,
127 isPrimary: true,
128 isForeign: false,
129 })
130 }
131 }
132
133 this.modulesMap.set(serviceName, mod as unknown as LoadedLinkModule)
134 }
135
136 private addRelationship(
137 serviceName: string,
138 relationship: RemoteRelationship
139 ): void {
140 const { primaryKey, foreignKey } = relationship
141
142 if (!this.relations.has(serviceName)) {
143 this.relations.set(serviceName, new Map())
144 }
145
146 const key = relationship.isPrimary ? primaryKey : foreignKey
147 const serviceMap = this.relations.get(serviceName)!
148 if (!serviceMap.has(key)) {
149 serviceMap.set(key, [])
150 }
151
152 serviceMap.get(key)!.push(relationship)
153 }
154
155 getLinkModule(
156 moduleA: string,
157 moduleAKey: string,
158 moduleB: string,
159 moduleBKey: string
160 ) {
161 const key = [moduleA, moduleAKey, moduleB, moduleBKey].join("-")
162 return this.relationsPairs.get(key)
163 }
164
165 getRelationships(): Map<string, Map<string, RemoteRelationship[]>> {
166 return this.relations
167 }
168
169 private getLinkableKeys(mod: LoadedLinkModule) {
170 return (
171 (mod.__joinerConfig.linkableKeys &&
172 Object.keys(mod.__joinerConfig.linkableKeys)) ||
173 mod.__joinerConfig.primaryKeys ||
174 []
175 )
176 }
177
178 private async executeCascade(
179 removedServices: DeleteEntityInput,
180 executionMethod: "softDelete" | "restore",
181 @MedusaContext() sharedContext: Context = {}
182 ): Promise<[CascadeError[] | null, RemovedIds]> {
183 const removedIds: RemovedIds = {}
184 const returnIdsList: RemovedIds = {}
185 const processedIds: Record<string, Set<string>> = {}
186
187 const services = Object.keys(removedServices).map((serviceName) => {
188 const deleteKeys = {}
189
190 for (const field in removedServices[serviceName]) {
191 deleteKeys[field] = Array.isArray(removedServices[serviceName][field])
192 ? removedServices[serviceName][field]
193 : [removedServices[serviceName][field]]
194 }
195
196 return { serviceName, deleteKeys }
197 })
198
199 const errors: CascadeError[] = []
200 const cascade = async (
201 services: { serviceName: string; deleteKeys: DeleteEntities }[],
202 isCascading: boolean = false
203 ): Promise<RemovedIds> => {
204 let method = executionMethod
205
206 if (errors.length) {
207 return returnIdsList
208 }
209
210 const servicePromises = services.map(async (serviceInfo) => {
211 const serviceRelations = this.relations.get(serviceInfo.serviceName)!
212
213 if (!serviceRelations) {
214 return
215 }
216
217 const values = serviceInfo.deleteKeys
218
219 const deletePromises: Promise<void>[] = []
220
221 for (const field in values) {
222 const relatedServices = serviceRelations.get(field)
223
224 if (!relatedServices || !values[field]?.length) {
225 continue
226 }
227
228 const relatedServicesPromises = relatedServices.map(
229 async (relatedService) => {
230 const { serviceName, primaryKey, args } = relatedService
231 const processedHash = `${serviceName}-${primaryKey}`
232
233 if (!processedIds[processedHash]) {
234 processedIds[processedHash] = new Set()
235 }
236
237 const unprocessedIds = values[field].filter(
238 (id) => !processedIds[processedHash].has(id)
239 )
240
241 if (!unprocessedIds.length) {
242 return
243 }
244
245 unprocessedIds.forEach((id) => {
246 processedIds[processedHash].add(id)
247 })
248
249 const cascadeDelKeys: DeleteEntities = {}
250 cascadeDelKeys[primaryKey] = unprocessedIds
251 const service: ILinkModule = this.modulesMap.get(serviceName)!
252
253 const returnFields = this.getLinkableKeys(
254 service as LoadedLinkModule
255 )
256
257 let deletedEntities: Record<string, string[]> = {}
258
259 try {
260 if (args?.methodSuffix) {
261 method += toPascalCase(args.methodSuffix)
262 }
263
264 const removed = await service[method](
265 cascadeDelKeys,
266 {
267 returnLinkableKeys: returnFields,
268 },
269 sharedContext
270 )
271
272 deletedEntities = removed as Record<string, string[]>
273 } catch (error) {
274 errors.push({
275 serviceName,
276 method,
277 args: cascadeDelKeys,
278 error: JSON.parse(
279 JSON.stringify(error, Object.getOwnPropertyNames(error))
280 ),
281 })
282 return
283 }
284
285 if (Object.keys(deletedEntities).length === 0) {
286 return
287 }
288
289 removedIds[serviceName] = {
290 ...deletedEntities,
291 }
292
293 if (!isCascading) {
294 returnIdsList[serviceName] = {
295 ...deletedEntities,
296 }
297 } else {
298 const [mainKey] = returnFields
299
300 if (!returnIdsList[serviceName]) {
301 returnIdsList[serviceName] = {}
302 }
303 if (!returnIdsList[serviceName][mainKey]) {
304 returnIdsList[serviceName][mainKey] = []
305 }
306
307 returnIdsList[serviceName][mainKey] = [
308 ...new Set(
309 returnIdsList[serviceName][mainKey].concat(
310 deletedEntities[mainKey]
311 )
312 ),
313 ]
314 }
315
316 Object.keys(deletedEntities).forEach((key) => {
317 deletedEntities[key].forEach((id) => {
318 const hash = `${serviceName}-${key}`
319 if (!processedIds[hash]) {
320 processedIds[hash] = new Set()
321 }
322
323 processedIds[hash].add(id)
324 })
325 })
326
327 await cascade(
328 [
329 {
330 serviceName: serviceName,
331 deleteKeys: deletedEntities as DeleteEntities,
332 },
333 ],
334 true
335 )
336 }
337 )
338
339 deletePromises.push(...relatedServicesPromises)
340 }
341
342 await promiseAll(deletePromises)
343 })
344
345 await promiseAll(servicePromises)
346 return returnIdsList
347 }
348
349 const result = await cascade(services)
350
351 return [errors.length ? errors : null, result]
352 }
353
354 private getLinkModuleOrThrow(link: LinkDefinition): LoadedLinkModule {
355 const mods = Object.keys(link).filter((attr) => attr !== "data")
356
357 if (mods.length > 2) {
358 throw new Error(`Only two modules can be linked.`)
359 }
360
361 const { moduleA, moduleB, moduleAKey, moduleBKey } =
362 this.getLinkDataConfig(link)
363 const service = this.getLinkModule(moduleA, moduleAKey, moduleB, moduleBKey)
364
365 if (!service) {
366 throw new Error(
367 linkingErrorMessage({
368 moduleA,
369 moduleAKey,
370 moduleB,
371 moduleBKey,
372 type: "link",
373 })
374 )
375 }
376
377 return service
378 }
379
380 private getLinkDataConfig(link: LinkDefinition): LinkDataConfig {
381 const moduleNames = Object.keys(link).filter((attr) => attr !== "data")
382 const [moduleA, moduleB] = moduleNames
383 const primaryKeys = Object.keys(link[moduleA])
384 const moduleAKey = primaryKeys.join(",")
385 const moduleBKey = Object.keys(link[moduleB]).join(",")
386
387 return {
388 moduleA,
389 moduleB,
390 primaryKeys,
391 moduleAKey,
392 moduleBKey,
393 }
394 }
395
396 async create(
397 link: LinkDefinition | LinkDefinition[],
398 @MedusaContext() sharedContext: Context = {}
399 ): Promise<unknown[]> {
400 const allLinks = Array.isArray(link) ? link : [link]
401 const serviceLinks = new Map<
402 string,
403 {
404 linksToCreate: [string | string[], string, Record<string, unknown>?][]
405 linksToValidateForUniqueness: {
406 filters: { [key: string]: any }[]
407 services: string[]
408 }
409 uniquePairsInBatch: Map<string, unknown>
410 }
411 >()
412
413 for (const link of allLinks) {
414 const service = this.getLinkModuleOrThrow(link)
415 const relationships = service.__joinerConfig.relationships
416 const { moduleA, moduleB, moduleBKey, primaryKeys } =
417 this.getLinkDataConfig(link)
418
419 if (!serviceLinks.has(service.__definition.key)) {
420 serviceLinks.set(service.__definition.key, {
421 /**
422 * Tuple of foreign key and the primary keys that must be
423 * persisted to the pivot table for representing the
424 * link
425 */
426 linksToCreate: [],
427
428 /**
429 * An array of objects to validate for uniqueness before persisting
430 * data to the pivot table. When a link uses "isList: false", we
431 * have to limit a relationship with this entity to be a one-to-one
432 * or one-to-many
433 */
434 linksToValidateForUniqueness: {
435 filters: [],
436 services: relationships?.map((r) => r.serviceName) ?? [],
437 },
438
439 /**
440 * Tracks, within this same create() call, which "other side" value
441 * a constrained foreign key value has already been paired with, so
442 * that two links in the same batch can't create an illegal
443 * many-to-one/one-to-one violation before either is persisted.
444 */
445 uniquePairsInBatch: new Map(),
446 })
447 }
448
449 /**
450 * When isList is set on false on the relationship, then it means
451 * we have a one-to-one or many-to-one relationship with the
452 * other side and we have limit duplicate entries from other
453 * entity. For example:
454 *
455 * - A brand has a many to one relationship with a product.
456 * - A product can have only one brand. Aka (brand.isList = false)
457 * - A brand can have multiple products. Aka (products.isList = true)
458 *
459 * A result of this, we have to ensure that a product_id can only appear
460 * once in the pivot table that is used for tracking "brand<>products"
461 * relationship.
462 */
463 const { linksToValidateForUniqueness, uniquePairsInBatch } =
464 serviceLinks.get(service.__definition.key)!
465
466 const modA = relationships?.[0]!
467 const modB = relationships?.[1]!
468
469 const assertUniqueInBatch = (
470 constrainedForeignKey: string,
471 constrainedValue: unknown,
472 pairValue: unknown
473 ) => {
474 const mapKey = `${constrainedForeignKey}:${constrainedValue}`
475 const existingPairValue = uniquePairsInBatch.get(mapKey)
476
477 if (
478 existingPairValue !== undefined &&
479 existingPairValue !== pairValue
480 ) {
481 const serviceA = linksToValidateForUniqueness.services[0]
482 const serviceB = linksToValidateForUniqueness.services[1]
483
484 throw new MedusaError(
485 MedusaError.Types.INVALID_DATA,
486 `Cannot create multiple links between '${serviceA}' and '${serviceB}'`
487 )
488 }
489
490 uniquePairsInBatch.set(mapKey, pairValue)
491 }
492
493 if (!modA.hasMany || !modB.hasMany) {
494 if (!modA.hasMany && !modB.hasMany) {
495 linksToValidateForUniqueness.filters.push({
496 $or: [
497 { [modA.foreignKey]: link[moduleA][modA.foreignKey] },
498 { [modB.foreignKey]: link[moduleB][modB.foreignKey] },
499 ],
500 })
501
502 assertUniqueInBatch(
503 modA.foreignKey,
504 link[moduleA][modA.foreignKey],
505 link[moduleB][modB.foreignKey]
506 )
507 assertUniqueInBatch(
508 modB.foreignKey,
509 link[moduleB][modB.foreignKey],
510 link[moduleA][modA.foreignKey]
511 )
512 } else if (!modA.hasMany) {
513 linksToValidateForUniqueness.filters.push({
514 [modA.foreignKey]: { $ne: link[moduleA][modA.foreignKey] },
515 [modB.foreignKey]: link[moduleB][modB.foreignKey],
516 })
517
518 assertUniqueInBatch(
519 modB.foreignKey,
520 link[moduleB][modB.foreignKey],
521 link[moduleA][modA.foreignKey]
522 )
523 } else if (!modB.hasMany) {
524 linksToValidateForUniqueness.filters.push({
525 [modB.foreignKey]: { $ne: link[moduleB][modB.foreignKey] },
526 [modA.foreignKey]: link[moduleA][modA.foreignKey],
527 })
528
529 assertUniqueInBatch(
530 modA.foreignKey,
531 link[moduleA][modA.foreignKey],
532 link[moduleB][modB.foreignKey]
533 )
534 }
535 }
536
537 const pkValue =
538 primaryKeys.length === 1
539 ? link[moduleA][primaryKeys[0]]
540 : primaryKeys.map((k) => link[moduleA][k])
541
542 const fields: unknown[] = [pkValue, link[moduleB][moduleBKey]]
543
544 if (isObject(link.data)) {
545 fields.push(link.data)
546 }
547
548 serviceLinks
549 .get(service.__definition.key)
550 ?.linksToCreate.push(fields as any)
551 }
552
553 for (const [serviceName, data] of serviceLinks) {
554 if (data.linksToValidateForUniqueness.filters.length) {
555 const service = this.modulesMap.get(serviceName)!
556 const existingLinks = await service.list(
557 {
558 $or: data.linksToValidateForUniqueness.filters,
559 },
560 {
561 take: 1,
562 },
563 sharedContext
564 )
565
566 if (existingLinks.length > 0) {
567 const serviceA = data.linksToValidateForUniqueness.services[0]
568 const serviceB = data.linksToValidateForUniqueness.services[1]
569
570 throw new MedusaError(
571 MedusaError.Types.INVALID_DATA,
572 `Cannot create multiple links between '${serviceA}' and '${serviceB}'`
573 )
574 }
575 }
576 }
577
578 const promises: Promise<unknown[]>[] = []
579 for (const [serviceName, data] of serviceLinks) {
580 const service = this.modulesMap.get(serviceName)!
581 promises.push(
582 service.create(data.linksToCreate, undefined, undefined, sharedContext)
583 )
584 }
585
586 return (await promiseAll(promises)).flat()
587 }
588
589 async dismiss(
590 link: LinkDefinition | LinkDefinition[],
591 @MedusaContext() sharedContext: Context = {}
592 ): Promise<unknown[]> {
593 const allLinks = Array.isArray(link) ? link : [link]
594 const serviceLinks = new Map<string, [string | string[], string][]>()
595
596 for (const link of allLinks) {
597 const service = this.getLinkModuleOrThrow(link)
598 const { moduleA, moduleB, moduleBKey, primaryKeys } =
599 this.getLinkDataConfig(link)
600
601 if (!serviceLinks.has(service.__definition.key)) {
602 serviceLinks.set(service.__definition.key, [])
603 }
604
605 const pkValue =
606 primaryKeys.length === 1
607 ? link[moduleA][primaryKeys[0]]
608 : primaryKeys.map((k) => link[moduleA][k])
609
610 serviceLinks
611 .get(service.__definition.key)
612 ?.push([pkValue, link[moduleB][moduleBKey]] as any)
613 }
614
615 const promises: Promise<unknown[]>[] = []
616
617 for (const [serviceName, links] of serviceLinks) {
618 const service = this.modulesMap.get(serviceName)!
619
620 promises.push(service.dismiss(links, undefined, sharedContext))
621 }
622
623 return (await promiseAll(promises)).flat()
624 }
625
626 async delete(
627 removedServices: DeleteEntityInput,
628 @MedusaContext() sharedContext: Context = {}
629 ): Promise<[CascadeError[] | null, RemovedIds]> {
630 return await this.executeCascade(
631 removedServices,
632 "softDelete",
633 sharedContext
634 )
635 }
636
637 async restore(
638 removedServices: DeleteEntityInput,
639 @MedusaContext() sharedContext: Context = {}
640 ): Promise<[CascadeError[] | null, RestoredIds]> {
641 return await this.executeCascade(removedServices, "restore", sharedContext)
642 }
643
644 async list(
645 link: LinkDefinition | LinkDefinition[],
646 options?: { asLinkDefinition?: boolean },
647 @MedusaContext() sharedContext: Context = {}
648 ): Promise<(object | LinkDefinition)[]> {
649 const allLinks = Array.isArray(link) ? link : [link]
650 const serviceLinks = new Map<string, object[]>()
651
652 for (const link of allLinks) {
653 const service = this.getLinkModuleOrThrow(link)
654 const { moduleA, moduleB } = this.getLinkDataConfig(link)
655
656 if (!serviceLinks.has(service.__definition.key)) {
657 serviceLinks.set(service.__definition.key, [])
658 }
659
660 serviceLinks.get(service.__definition.key)?.push({
661 ...link[moduleA],
662 ...link[moduleB],
663 })
664 }
665
666 const promises: Promise<object[]>[] = []
667
668 for (const [serviceName, filters] of serviceLinks) {
669 const service = this.modulesMap.get(serviceName)!
670
671 promises.push(
672 service
673 .list({ $or: filters }, {}, sharedContext)
674 .then((links: any[]) =>
675 options?.asLinkDefinition
676 ? convertRecordsToLinkDefinition(links, service)
677 : links
678 )
679 )
680 }
681
682 return (await promiseAll(promises)).flat()
683 }
684 }