Raw
1 import { MedusaModule } from "@medusajs/framework/modules-sdk"
2 import {
3 IndexTypes,
4 JoinerServiceConfigAlias,
5 ModuleJoinerConfig,
6 ModuleJoinerRelationship,
7 } from "@medusajs/framework/types"
8 import {
9 buildModuleResourceEventName,
10 CommonEvents,
11 GraphQLUtils,
12 kebabCase,
13 lowerCaseFirst,
14 } from "@medusajs/framework/utils"
15 import { schemaObjectRepresentationPropertiesToOmit } from "@types"
16 import { baseGraphqlSchema } from "./base-graphql-schema"
17
18 export const CustomDirectives = {
19 Listeners: {
20 configurationPropertyName: "listeners",
21 isRequired: true,
22 name: "Listeners",
23 directive: "@Listeners",
24 definition: "directive @Listeners (values: [String!]) on OBJECT",
25 },
26 }
27
28 export function makeSchemaExecutable(inputSchema: string) {
29 const { schema: cleanedSchema } = GraphQLUtils.cleanGraphQLSchema(inputSchema)
30
31 if (!cleanedSchema) {
32 return
33 }
34
35 return GraphQLUtils.makeExecutableSchema({
36 typeDefs: cleanedSchema,
37 })
38 }
39
40 /**
41 * Retrieve the property name of the source entity that corresponds to the target entity
42 * @param sourceEntityName - The name of the source entity
43 * @param targetEntityName - The name of the target entity
44 * @param entitiesMap - The map of entities configured in the module
45 * @param servicesEntityMap - The map of entities configured in the services
46 * @param node - The node of the source entity
47 * @returns The property name and if it is an array of the source entity property that corresponds to the target entity
48 */
49 function retrieveEntityPropByType({
50 sourceEntityName,
51 targetEntityName,
52 entitiesMap,
53 servicesEntityMap,
54 node,
55 }: {
56 sourceEntityName?: string
57 targetEntityName: string
58 entitiesMap?: Record<string, any>
59 servicesEntityMap?: Record<string, any>
60 node?: any
61 }): { name: string; isArray: boolean } | undefined {
62 if (!node && !entitiesMap && !servicesEntityMap) {
63 throw new Error(
64 "Index Module error, unable to retrieve the entity property by type. Please provide either the entitiesMap and servicesEntityMap or the node."
65 )
66 }
67
68 const retrieveFieldNode = (
69 node: any
70 ): { name: string; isArray: boolean } | undefined => {
71 const astNode = node?.astNode
72 const fields = astNode?.fields ?? []
73
74 for (const field of fields) {
75 let type = field.type
76 let isArray = false
77 while (type.type) {
78 if (type.kind === GraphQLUtils.Kind.LIST_TYPE) {
79 isArray = true
80 }
81 type = type.type
82 }
83 if (type.name?.value === targetEntityName) {
84 return { name: field.name?.value, isArray }
85 }
86 }
87
88 return
89 }
90
91 let prop: any
92 if (node) {
93 prop = retrieveFieldNode(node)
94 }
95
96 if (entitiesMap && !prop) {
97 prop = retrieveFieldNode(entitiesMap[sourceEntityName!])
98 }
99
100 if (servicesEntityMap && !prop) {
101 prop = retrieveFieldNode(servicesEntityMap[sourceEntityName!])
102 }
103
104 return (
105 prop && {
106 name: prop?.name,
107 isArray: prop?.isArray,
108 }
109 )
110 }
111
112 function extractNameFromAlias(
113 alias: JoinerServiceConfigAlias | JoinerServiceConfigAlias[]
114 ) {
115 const alias_ = Array.isArray(alias) ? alias[0] : alias
116 const names = Array.isArray(alias_?.name) ? alias_?.name : [alias_?.name]
117 return names[0]
118 }
119
120 function retrieveAliasForEntity(entityName: string, aliases) {
121 aliases = aliases ? (Array.isArray(aliases) ? aliases : [aliases]) : []
122
123 for (const alias of aliases) {
124 const names = Array.isArray(alias.name) ? alias.name : [alias.name]
125
126 if (alias.entity === entityName) {
127 return names[0]
128 }
129
130 for (const name of names) {
131 if (name.toLowerCase() === entityName.toLowerCase()) {
132 return name
133 }
134 }
135 }
136 }
137
138 function retrieveModuleAndAlias(entityName, moduleJoinerConfigs) {
139 let relatedModule
140 let alias
141
142 for (const moduleJoinerConfig of moduleJoinerConfigs) {
143 const moduleSchema = moduleJoinerConfig.schema
144 const moduleAliases = moduleJoinerConfig.alias
145
146 /**
147 * If the entity exist in the module schema, then the current module is the
148 * one we are looking for.
149 *
150 * If the module does not have any schema, then we need to base the search
151 * on the provided aliases. in any case, we try to get both
152 */
153
154 if (moduleSchema) {
155 const executableSchema = makeSchemaExecutable(moduleSchema)
156 const entitiesMap = executableSchema?.getTypeMap()
157
158 if (entitiesMap?.[entityName]) {
159 relatedModule = moduleJoinerConfig
160 }
161 }
162
163 if (relatedModule && moduleAliases) {
164 alias = retrieveAliasForEntity(entityName, moduleJoinerConfig.alias)
165 }
166
167 if (relatedModule) {
168 break
169 }
170 }
171
172 if (!relatedModule) {
173 return { relatedModule: null, alias: null }
174 }
175
176 if (!alias) {
177 throw new Error(
178 `Index Module error, the module ${relatedModule?.serviceName} has a schema but does not have any alias for the entity ${entityName}. Please add an alias to the module configuration and the entity it correspond to in the args under the entity property.`
179 )
180 }
181
182 return { relatedModule, alias }
183 }
184
185 // TODO: rename util
186 function retrieveLinkModuleAndAlias({
187 primaryEntity,
188 primaryModuleConfig,
189 foreignEntity,
190 foreignModuleConfig,
191 moduleJoinerConfigs,
192 servicesEntityMap,
193 entitiesMap,
194 }: {
195 primaryEntity: string
196 primaryModuleConfig: ModuleJoinerConfig
197 foreignEntity: string
198 foreignModuleConfig: ModuleJoinerConfig
199 moduleJoinerConfigs: ModuleJoinerConfig[]
200 servicesEntityMap: Record<string, any>
201 entitiesMap: Record<string, any>
202 }): {
203 entityName: string
204 alias: string
205 linkModuleConfig: ModuleJoinerConfig
206 intermediateEntityNames: string[]
207 isInverse?: boolean
208 isList?: boolean
209 inverseSideProp?: string
210 }[] {
211 const linkModulesMetadata: {
212 entityName: string
213 alias: string
214 linkModuleConfig: ModuleJoinerConfig
215 intermediateEntityNames: string[]
216 isInverse?: boolean
217 inverseSideProp?: string
218 isList?: boolean
219 }[] = []
220
221 for (const linkModuleJoinerConfig of moduleJoinerConfigs.filter(
222 (config) => config.isLink && !config.isReadOnlyLink
223 )) {
224 const linkPrimary =
225 linkModuleJoinerConfig.relationships![0] as ModuleJoinerRelationship
226 const linkForeign =
227 linkModuleJoinerConfig.relationships![1] as ModuleJoinerRelationship
228
229 const isDirectMatch =
230 linkPrimary.serviceName === primaryModuleConfig.serviceName &&
231 linkForeign.serviceName === foreignModuleConfig.serviceName &&
232 linkPrimary.entity === primaryEntity
233
234 const isInverseMatch =
235 linkPrimary.serviceName === foreignModuleConfig.serviceName &&
236 linkForeign.serviceName === primaryModuleConfig.serviceName &&
237 linkPrimary.entity === foreignEntity
238
239 if (!(isDirectMatch || isInverseMatch)) {
240 continue
241 }
242
243 const primaryEntityLinkableKey = isDirectMatch
244 ? linkPrimary.foreignKey
245 : linkForeign.foreignKey
246 const isTheForeignKeyEntityEqualPrimaryEntity =
247 primaryModuleConfig.linkableKeys?.[primaryEntityLinkableKey] ===
248 primaryEntity
249
250 const foreignEntityLinkableKey = isDirectMatch
251 ? linkForeign.foreignKey
252 : linkPrimary.foreignKey
253 const isTheForeignKeyEntityEqualForeignEntity =
254 foreignModuleConfig.linkableKeys?.[foreignEntityLinkableKey] ===
255 foreignEntity
256
257 const relationshipsTypes =
258 linkModuleJoinerConfig.relationships
259 ?.map((relationship) => relationship.entity!)
260 .filter(Boolean) ?? []
261
262 const filteredEntitiesMap = {
263 [linkModuleJoinerConfig.alias?.[0].entity]:
264 entitiesMap[linkModuleJoinerConfig.alias?.[0].entity],
265 }
266 const filteredServicesEntityMap = {
267 [linkModuleJoinerConfig.alias?.[0].entity]:
268 servicesEntityMap[linkModuleJoinerConfig.alias?.[0].entity],
269 }
270
271 for (const relationshipType of relationshipsTypes) {
272 filteredEntitiesMap[relationshipType] = entitiesMap[relationshipType]
273 filteredServicesEntityMap[relationshipType] =
274 servicesEntityMap[relationshipType]
275 }
276
277 const linkName = linkModuleJoinerConfig.extends?.find((extend) => {
278 return (
279 (extend.serviceName === primaryModuleConfig.serviceName ||
280 extend.relationship.serviceName ===
281 foreignModuleConfig.serviceName) &&
282 (extend.relationship.primaryKey === primaryEntityLinkableKey ||
283 extend.relationship.primaryKey === foreignEntityLinkableKey)
284 )
285 })?.relationship.serviceName
286
287 if (!linkName) {
288 throw new Error(
289 `Index Module error, unable to retrieve the link module name for the services ${primaryModuleConfig.serviceName} - ${foreignModuleConfig.serviceName}. Please be sure that the extend relationship service name is set correctly`
290 )
291 }
292
293 if (!linkModuleJoinerConfig.alias?.[0]?.entity) {
294 throw new Error(
295 `Index Module error, unable to retrieve the link module entity name for the services ${primaryModuleConfig.serviceName} - ${foreignModuleConfig.serviceName}. Please be sure that the link module alias has an entity property in the args.`
296 )
297 }
298
299 if (
300 isTheForeignKeyEntityEqualPrimaryEntity &&
301 isTheForeignKeyEntityEqualForeignEntity
302 ) {
303 /**
304 * The link will become the parent of the foreign entity, that is why the alias must be the one that correspond to the extended foreign module
305 */
306
307 const inverseSideProp = retrieveEntityPropByType({
308 targetEntityName: primaryEntity,
309 sourceEntityName: linkModuleJoinerConfig.alias[0].entity,
310 servicesEntityMap: filteredServicesEntityMap,
311 entitiesMap: filteredEntitiesMap,
312 })
313
314 linkModulesMetadata.push({
315 entityName: linkModuleJoinerConfig.alias[0].entity,
316 alias: extractNameFromAlias(linkModuleJoinerConfig.alias),
317 linkModuleConfig: linkModuleJoinerConfig,
318 intermediateEntityNames: [],
319 isInverse: isInverseMatch,
320 isList: inverseSideProp?.isArray,
321 inverseSideProp: inverseSideProp?.name,
322 })
323 } else {
324 const intermediateEntityName =
325 foreignModuleConfig.linkableKeys![foreignEntityLinkableKey]
326
327 const moduleSchema = isDirectMatch
328 ? foreignModuleConfig.schema!
329 : primaryModuleConfig.schema!
330
331 if (!moduleSchema) {
332 throw new Error(
333 `Index Module error, unable to retrieve the intermediate entity name for the services ${primaryModuleConfig.serviceName} - ${foreignModuleConfig.serviceName}. Please be sure that the foreign module ${foreignModuleConfig.serviceName} has a schema.`
334 )
335 }
336
337 const entitiesMap = servicesEntityMap
338 let intermediateEntities: string[] = []
339 let foundCount = 0
340 let foundName: string | null = null
341 const isForeignEntityChildOfIntermediateEntity = (
342 entityName: string,
343 visited: Set<string> = new Set()
344 ): boolean => {
345 if (visited.has(entityName)) {
346 return false
347 }
348 visited.add(entityName)
349
350 for (const entityType of Object.values(entitiesMap)) {
351 const inverseSideProp = retrieveEntityPropByType({
352 node: entityType,
353 targetEntityName: entityName,
354 })
355
356 if (
357 entityType.astNode?.kind === "ObjectTypeDefinition" &&
358 inverseSideProp
359 ) {
360 if (entityType.name === intermediateEntityName) {
361 foundName = entityType.name
362 ++foundCount
363 return true
364 } else {
365 const inverseSideProp = isForeignEntityChildOfIntermediateEntity(
366 entityType.name,
367 visited
368 )
369 if (inverseSideProp) {
370 intermediateEntities.push(entityType.name)
371 return true
372 }
373 }
374 }
375 }
376 return false
377 }
378
379 isForeignEntityChildOfIntermediateEntity(
380 isDirectMatch ? foreignEntity : primaryEntity
381 )
382
383 if (foundCount !== 1) {
384 throw new Error(
385 `Index Module error, unable to retrieve the intermediate entities for the services ${
386 primaryModuleConfig.serviceName
387 } - ${foreignModuleConfig.serviceName} between ${
388 isDirectMatch ? foreignEntity : primaryEntity
389 } and ${intermediateEntityName}. Multiple paths or no path found. Please check your schema in ${
390 foreignModuleConfig.serviceName
391 }`
392 )
393 }
394
395 intermediateEntities.push(foundName!)
396
397 /**
398 * The link will become the parent of the foreign entity, that is why the alias must be the one that correspond to the extended foreign module
399 */
400
401 const directInverseSideProp = retrieveEntityPropByType({
402 targetEntityName: isDirectMatch
403 ? primaryEntity
404 : linkModuleJoinerConfig.alias[0].entity,
405 sourceEntityName: isDirectMatch
406 ? linkModuleJoinerConfig.alias[0].entity
407 : primaryEntity,
408 servicesEntityMap: filteredServicesEntityMap,
409 entitiesMap: filteredEntitiesMap,
410 })
411
412 linkModulesMetadata.push({
413 entityName: linkModuleJoinerConfig.alias[0].entity,
414 alias: extractNameFromAlias(linkModuleJoinerConfig.alias),
415 linkModuleConfig: linkModuleJoinerConfig,
416 intermediateEntityNames: intermediateEntities,
417 inverseSideProp: directInverseSideProp?.name,
418 isList: directInverseSideProp?.isArray,
419 isInverse: isInverseMatch,
420 })
421 }
422 }
423
424 if (!linkModulesMetadata.length) {
425 console.warn(
426 `Index Module warning, unable to retrieve the link module that correspond to the entities ${primaryEntity} - ${foreignEntity}.`
427 )
428 }
429
430 return linkModulesMetadata
431 }
432
433 function getObjectRepresentationRef(
434 entityName,
435 { objectRepresentationRef }
436 ): IndexTypes.SchemaObjectEntityRepresentation {
437 return (objectRepresentationRef[entityName] ??= {
438 entity: entityName,
439 parents: [],
440 alias: "",
441 listeners: [],
442 moduleConfig: null,
443 fields: [],
444 })
445 }
446
447 function setCustomDirectives(currentObjectRepresentationRef, directives) {
448 for (const customDirectiveConfiguration of Object.values(CustomDirectives)) {
449 const directive = directives.find(
450 (typeDirective) =>
451 typeDirective.name.value === customDirectiveConfiguration.name
452 )
453
454 if (!directive) {
455 return
456 }
457
458 // Only support array directive value for now
459 currentObjectRepresentationRef[
460 customDirectiveConfiguration.configurationPropertyName
461 ] = ((directive.arguments[0].value as any)?.values ?? []).map(
462 (v) => v.value
463 )
464 }
465 }
466
467 function processEntity(
468 entityName: string,
469 {
470 entitiesMap,
471 servicesEntityMap,
472 moduleJoinerConfigs,
473 objectRepresentationRef,
474 }: {
475 entitiesMap: any
476 servicesEntityMap: any
477 moduleJoinerConfigs: ModuleJoinerConfig[]
478 objectRepresentationRef: IndexTypes.SchemaObjectRepresentation
479 }
480 ) {
481 /**
482 * Get the reference to the object representation for the current entity.
483 */
484
485 const currentObjectRepresentationRef = getObjectRepresentationRef(
486 entityName,
487 {
488 objectRepresentationRef,
489 }
490 )
491
492 /**
493 * Retrieve and set the custom directives for the current entity.
494 */
495
496 setCustomDirectives(
497 currentObjectRepresentationRef,
498 entitiesMap[entityName].astNode?.directives ?? []
499 )
500
501 // Merge and deduplicate the fields
502 currentObjectRepresentationRef.fields ??= []
503 currentObjectRepresentationRef.fields =
504 currentObjectRepresentationRef.fields.concat(
505 ...(GraphQLUtils.gqlGetFieldsAndRelations(entitiesMap, entityName) ?? [])
506 )
507 currentObjectRepresentationRef.fields = Array.from(
508 new Set(currentObjectRepresentationRef.fields)
509 )
510
511 /**
512 * Retrieve the module and alias for the current entity.
513 */
514
515 const { relatedModule: currentEntityModule, alias } = retrieveModuleAndAlias(
516 entityName,
517 moduleJoinerConfigs
518 )
519
520 if (
521 !currentEntityModule &&
522 currentObjectRepresentationRef.listeners.length > 0
523 ) {
524 const example = JSON.stringify({
525 alias: [
526 {
527 name: "entity-alias",
528 entity: entityName,
529 },
530 ],
531 })
532 throw new Error(
533 `Index Module error, unable to retrieve the module that corresponds to the entity ${entityName}.\nPlease add the entity to the module schema or add an alias to the joiner config like the example below:\n${example}`
534 )
535 }
536
537 if (currentEntityModule) {
538 objectRepresentationRef._serviceNameModuleConfigMap[
539 currentEntityModule.serviceName
540 ] = currentEntityModule
541 currentObjectRepresentationRef.moduleConfig = currentEntityModule
542 currentObjectRepresentationRef.alias = alias
543 }
544 /**
545 * Retrieve the parent entities for the current entity.
546 */
547
548 const schemaParentEntity = Object.values(entitiesMap).filter((value: any) => {
549 return (
550 value.astNode &&
551 (value.astNode as GraphQLUtils.ObjectTypeDefinitionNode).fields?.some(
552 (field: any) => {
553 let currentType = field.type
554 while (currentType.type) {
555 currentType = currentType.type
556 }
557
558 return currentType.name?.value === entityName
559 }
560 )
561 )
562 })
563
564 if (!schemaParentEntity.length) {
565 return
566 }
567
568 /**
569 * If the current entity has parent entities, then we need to process them.
570 */
571 const parentEntityNames = schemaParentEntity.map((parent: any) => {
572 return parent.name
573 })
574
575 for (const parent of parentEntityNames) {
576 /**
577 * Retrieve the parent entity field in the schema
578 */
579
580 const entityFieldInParent = retrieveEntityPropByType({
581 sourceEntityName: parent,
582 targetEntityName: entityName,
583 entitiesMap,
584 servicesEntityMap,
585 })!
586
587 const entityTargetPropertyNameInParent = entityFieldInParent.name
588 const entityTargetPropertyIsListInParent = entityFieldInParent.isArray
589
590 /**
591 * Retrieve the parent entity object representation reference.
592 */
593 if (!objectRepresentationRef[parent]) {
594 processEntity(parent, {
595 entitiesMap,
596 servicesEntityMap,
597 moduleJoinerConfigs,
598 objectRepresentationRef,
599 })
600 }
601
602 const parentObjectRepresentationRef = getObjectRepresentationRef(parent, {
603 objectRepresentationRef,
604 })
605 const parentModuleConfig = parentObjectRepresentationRef.moduleConfig
606
607 // If the entity is not part of any module, just set the parent and continue
608 if (!currentObjectRepresentationRef.moduleConfig) {
609 const parentAlreadyExists = currentObjectRepresentationRef.parents.some(
610 (existingParent) =>
611 existingParent.ref?.entity === parentObjectRepresentationRef.entity &&
612 existingParent.targetProp === entityTargetPropertyNameInParent
613 )
614
615 const parentPropertyNameWithinCurrentEntity = retrieveEntityPropByType({
616 sourceEntityName: entityName,
617 targetEntityName: parent,
618 entitiesMap,
619 servicesEntityMap,
620 })
621
622 if (!parentAlreadyExists) {
623 currentObjectRepresentationRef.parents.push({
624 ref: parentObjectRepresentationRef,
625 targetProp: entityTargetPropertyNameInParent,
626 inverseSideProp: parentPropertyNameWithinCurrentEntity?.name!,
627 isList: entityTargetPropertyIsListInParent,
628 })
629 } else {
630 return
631 }
632
633 continue
634 }
635
636 /**
637 * If the parent entity and the current entity are part of the same service then configure the parent and
638 * add the parent id as a field to the current entity.
639 */
640
641 if (
642 currentObjectRepresentationRef.moduleConfig.serviceName ===
643 parentModuleConfig.serviceName ||
644 parentModuleConfig.isLink ||
645 currentObjectRepresentationRef.moduleConfig.isLink
646 ) {
647 const parentPropertyNameWithinCurrentEntity = retrieveEntityPropByType({
648 sourceEntityName: entityName,
649 targetEntityName: parent,
650 entitiesMap,
651 servicesEntityMap,
652 })
653
654 const parentAlreadyExists = currentObjectRepresentationRef.parents.some(
655 (existingParent) =>
656 existingParent.ref?.entity === parentObjectRepresentationRef.entity &&
657 existingParent.targetProp === entityTargetPropertyNameInParent
658 )
659
660 if (!parentAlreadyExists) {
661 currentObjectRepresentationRef.parents.push({
662 ref: parentObjectRepresentationRef,
663 targetProp: entityTargetPropertyNameInParent,
664 inverseSideProp: parentPropertyNameWithinCurrentEntity?.name!,
665 isList: entityTargetPropertyIsListInParent,
666 })
667 }
668
669 const propertyToAdd = parentPropertyNameWithinCurrentEntity?.name + ".id"
670
671 if (
672 parentPropertyNameWithinCurrentEntity &&
673 !currentObjectRepresentationRef.fields.includes(propertyToAdd)
674 ) {
675 currentObjectRepresentationRef.fields.push(propertyToAdd)
676 }
677
678 if (parentAlreadyExists) {
679 return
680 }
681 } else {
682 /**
683 * If the parent entity and the current entity are not part of the same service then we need to
684 * find the link module that join them.
685 */
686
687 const linkModuleMetadatas = retrieveLinkModuleAndAlias({
688 primaryEntity: parentObjectRepresentationRef.entity,
689 primaryModuleConfig: parentModuleConfig,
690 foreignEntity: currentObjectRepresentationRef.entity,
691 foreignModuleConfig: currentEntityModule,
692 moduleJoinerConfigs,
693 servicesEntityMap,
694 entitiesMap,
695 })
696
697 for (const linkModuleMetadata of linkModuleMetadatas) {
698 const linkObjectRepresentationRef = getObjectRepresentationRef(
699 linkModuleMetadata.entityName,
700 { objectRepresentationRef }
701 )
702
703 objectRepresentationRef._serviceNameModuleConfigMap[
704 linkModuleMetadata.linkModuleConfig.serviceName ||
705 linkModuleMetadata.entityName
706 ] = linkModuleMetadata.linkModuleConfig
707
708 /**
709 * Add the schema parent entity as a parent to the link module and configure it.
710 */
711
712 linkObjectRepresentationRef.parents ??= []
713
714 if (
715 !linkObjectRepresentationRef.parents.some(
716 (parent) =>
717 parent.ref.entity === parentObjectRepresentationRef.entity
718 )
719 ) {
720 linkObjectRepresentationRef.parents.push({
721 ref: parentObjectRepresentationRef,
722 targetProp: linkModuleMetadata.alias,
723 inverseSideProp: linkModuleMetadata.inverseSideProp ?? "",
724 isList: linkModuleMetadata.isList,
725 isInverse: linkModuleMetadata.isInverse,
726 })
727 }
728 linkObjectRepresentationRef.alias = linkModuleMetadata.alias
729 linkObjectRepresentationRef.listeners = [
730 `${linkModuleMetadata.entityName}.${CommonEvents.ATTACHED}`,
731 `${linkModuleMetadata.entityName}.${CommonEvents.DETACHED}`,
732 ]
733 linkObjectRepresentationRef.moduleConfig =
734 linkModuleMetadata.linkModuleConfig
735
736 linkObjectRepresentationRef.fields = [
737 "id",
738 ...linkModuleMetadata.linkModuleConfig
739 .relationships!.map(
740 (relationship) =>
741 [
742 parentModuleConfig.serviceName,
743 currentEntityModule.serviceName,
744 ].includes(relationship.serviceName) && relationship.foreignKey
745 )
746 .filter((v): v is string => Boolean(v)),
747 ]
748
749 /**
750 * If the current entity is not the entity that is used to join the link module and the parent entity
751 * then we need to add the new entity that join them and then add the link as its parent
752 * before setting the new entity as the true parent of the current entity.
753 */
754
755 for (
756 let i = linkModuleMetadata.intermediateEntityNames.length - 1;
757 i >= 0;
758 --i
759 ) {
760 const intermediateEntityName =
761 linkModuleMetadata.intermediateEntityNames[i]
762
763 const isLastIntermediateEntity =
764 i === linkModuleMetadata.intermediateEntityNames.length - 1
765
766 const parentIntermediateEntityRef = isLastIntermediateEntity
767 ? linkObjectRepresentationRef
768 : objectRepresentationRef[
769 linkModuleMetadata.intermediateEntityNames[i + 1]
770 ]
771
772 const {
773 relatedModule: intermediateEntityModule,
774 alias: intermediateEntityAlias,
775 } = retrieveModuleAndAlias(
776 intermediateEntityName,
777 moduleJoinerConfigs
778 )
779
780 const intermediateEntityObjectRepresentationRef =
781 getObjectRepresentationRef(intermediateEntityName, {
782 objectRepresentationRef,
783 })
784
785 objectRepresentationRef._serviceNameModuleConfigMap[
786 intermediateEntityModule.serviceName
787 ] = intermediateEntityModule
788
789 const parentPropertyNameWithinIntermediateEntity =
790 retrieveEntityPropByType({
791 sourceEntityName: intermediateEntityName,
792 targetEntityName: parentIntermediateEntityRef.entity,
793 entitiesMap: entitiesMap,
794 servicesEntityMap: servicesEntityMap,
795 })
796
797 const intermediateEntityTargetPropertyIsListInParent =
798 retrieveEntityPropByType({
799 sourceEntityName: parentIntermediateEntityRef.entity,
800 targetEntityName: intermediateEntityName,
801 entitiesMap: entitiesMap,
802 servicesEntityMap: servicesEntityMap,
803 })?.isArray
804
805 const parentRef = {
806 ref: parentIntermediateEntityRef,
807 targetProp: intermediateEntityAlias,
808 inverseSideProp: parentPropertyNameWithinIntermediateEntity?.name!,
809 isList: intermediateEntityTargetPropertyIsListInParent,
810 }
811
812 const parentAlreadyExists =
813 intermediateEntityObjectRepresentationRef.parents.some(
814 (existingParent) =>
815 existingParent.ref?.entity ===
816 parentIntermediateEntityRef.entity &&
817 existingParent.targetProp === intermediateEntityAlias
818 )
819
820 if (!parentAlreadyExists) {
821 intermediateEntityObjectRepresentationRef.parents.push(parentRef)
822 }
823
824 intermediateEntityObjectRepresentationRef.alias =
825 intermediateEntityAlias
826 const kebabCasedServiceName = lowerCaseFirst(
827 kebabCase(intermediateEntityModule.serviceName)
828 )
829 intermediateEntityObjectRepresentationRef.listeners = [
830 buildModuleResourceEventName({
831 action: CommonEvents.CREATED,
832 objectName: intermediateEntityName,
833 prefix: kebabCasedServiceName,
834 }),
835 buildModuleResourceEventName({
836 action: CommonEvents.UPDATED,
837 objectName: intermediateEntityName,
838 prefix: kebabCasedServiceName,
839 }),
840 buildModuleResourceEventName({
841 action: CommonEvents.DELETED,
842 objectName: intermediateEntityName,
843 prefix: kebabCasedServiceName,
844 }),
845 buildModuleResourceEventName({
846 action: CommonEvents.RESTORED,
847 objectName: intermediateEntityName,
848 prefix: kebabCasedServiceName,
849 }),
850 ]
851 intermediateEntityObjectRepresentationRef.moduleConfig =
852 intermediateEntityModule
853 if (
854 !intermediateEntityObjectRepresentationRef.fields.includes("id")
855 ) {
856 intermediateEntityObjectRepresentationRef.fields.push("id")
857 }
858
859 /**
860 * We push the parent id only between intermediate entities but not between intermediate and link
861 */
862
863 if (!isLastIntermediateEntity) {
864 const propertyToAdd =
865 parentPropertyNameWithinIntermediateEntity?.name + ".id"
866
867 if (
868 parentPropertyNameWithinIntermediateEntity &&
869 !intermediateEntityObjectRepresentationRef.fields.includes(
870 propertyToAdd
871 )
872 ) {
873 intermediateEntityObjectRepresentationRef.fields.push(
874 propertyToAdd
875 )
876 }
877 }
878 }
879
880 /**
881 * If there is any intermediate entity then we need to set the last one as the parent field for the current entity.
882 * otherwise there is not need to set the link id field into the current entity.
883 */
884
885 let currentParentIntermediateRef = linkObjectRepresentationRef
886 if (linkModuleMetadata.intermediateEntityNames.length) {
887 currentParentIntermediateRef =
888 objectRepresentationRef[
889 linkModuleMetadata.intermediateEntityNames[0]
890 ]
891
892 const parentPropertyNameWithinCurrentEntity =
893 retrieveEntityPropByType({
894 sourceEntityName: currentObjectRepresentationRef.entity,
895 targetEntityName: currentParentIntermediateRef.entity,
896 entitiesMap: servicesEntityMap,
897 })
898
899 const propertyToAdd =
900 parentPropertyNameWithinCurrentEntity?.name + ".id"
901
902 if (
903 parentPropertyNameWithinCurrentEntity &&
904 !currentObjectRepresentationRef.fields.includes(propertyToAdd)
905 ) {
906 currentObjectRepresentationRef.fields.push(propertyToAdd)
907 }
908 }
909
910 const parentPropertyNameWithinCurrentEntity = retrieveEntityPropByType({
911 sourceEntityName: currentObjectRepresentationRef.entity,
912 targetEntityName: currentParentIntermediateRef.entity,
913 entitiesMap: servicesEntityMap,
914 })
915
916 const entityTargetPropertyIsListInParent = retrieveEntityPropByType({
917 sourceEntityName: currentParentIntermediateRef.entity,
918 targetEntityName: currentObjectRepresentationRef.entity,
919 entitiesMap: entitiesMap,
920 servicesEntityMap: servicesEntityMap,
921 })?.isArray
922
923 const existingParent = currentObjectRepresentationRef.parents.find(
924 (existingParent) =>
925 existingParent.ref?.entity ===
926 currentParentIntermediateRef.entity &&
927 existingParent.targetProp === entityTargetPropertyNameInParent
928 )
929
930 if (!existingParent) {
931 currentObjectRepresentationRef.parents.push({
932 ref: currentParentIntermediateRef,
933 inSchemaRef: parentObjectRepresentationRef,
934 targetProp: entityTargetPropertyNameInParent,
935 inverseSideProp: parentPropertyNameWithinCurrentEntity?.name!,
936 isList: entityTargetPropertyIsListInParent,
937 })
938 } else if (!existingParent.inSchemaRef) {
939 existingParent.inSchemaRef = parentObjectRepresentationRef
940 }
941 }
942 }
943 }
944 }
945
946 function getServicesEntityMap(
947 moduleJoinerConfigs,
948 addtionalSchema: string = ""
949 ) {
950 return makeSchemaExecutable(
951 baseGraphqlSchema +
952 "\n" +
953 moduleJoinerConfigs
954 .map((joinerConfig) => joinerConfig?.schema ?? "")
955 .join("\n") +
956 "\n" +
957 addtionalSchema
958 )!.getTypeMap()
959 }
960
961 /**
962 * Build a special object which will be used to retrieve the correct
963 * object representation using path tree
964 *
965 * @example
966 * {
967 * _schemaPropertiesMap: {
968 * "product": <ProductRef>
969 * "product.variants": <ProductVariantRef>
970 * }
971 * }
972 */
973
974 function buildAliasMap(
975 objectRepresentation: IndexTypes.SchemaObjectRepresentation
976 ) {
977 const aliasMap: IndexTypes.SchemaObjectRepresentation["_schemaPropertiesMap"] =
978 {}
979
980 function recursivelyBuildAliasPath(
981 current: IndexTypes.SchemaObjectEntityRepresentation,
982 parentPath = "",
983 aliases: {
984 alias: string
985 shortCutOf?: string
986 isInverse?: boolean
987 isList?: boolean
988 }[] = [],
989 visited: Set<string> = new Set(),
990 pathStack: string[] = []
991 ): {
992 alias: string
993 shortCutOf?: string
994 isInverse?: boolean
995 isList?: boolean
996 }[] {
997 const pathIdentifier = `${current.entity}:${parentPath}`
998
999 if (pathStack.includes(pathIdentifier)) {
1000 return []
1001 }
1002
1003 pathStack.push(pathIdentifier)
1004
1005 if (visited.has(current.entity)) {
1006 pathStack.pop()
1007 return []
1008 }
1009
1010 visited.add(current.entity)
1011
1012 for (const parentEntity of current.parents) {
1013 const newParentPath = parentPath
1014 ? `${parentEntity.targetProp}.${parentPath}`
1015 : parentEntity.targetProp
1016
1017 const newVisited = new Set(visited)
1018 const newPathStack = [...pathStack]
1019
1020 const parentAliases = recursivelyBuildAliasPath(
1021 parentEntity.ref,
1022 newParentPath,
1023 [],
1024 newVisited,
1025 newPathStack
1026 ).map((aliasObj) => ({
1027 alias: aliasObj.alias,
1028 isInverse: parentEntity.isInverse,
1029 isList: parentEntity.isList,
1030 }))
1031
1032 aliases.push(...parentAliases)
1033
1034 // Handle shortcut paths via inSchemaRef
1035 if (parentEntity.inSchemaRef) {
1036 const shortCutOf = parentAliases[0]
1037 if (!shortCutOf) {
1038 continue
1039 }
1040
1041 const shortcutAliases_ = recursivelyBuildAliasPath(
1042 parentEntity.inSchemaRef,
1043 newParentPath,
1044 [],
1045 new Set(visited),
1046 [...pathStack]
1047 )
1048
1049 // Assign all shortcut aliases to the parent aliases
1050 const shortcutAliases: any[] = []
1051 shortcutAliases_.forEach((shortcutAlias) => {
1052 parentAliases.forEach((aliasObj) => {
1053 let isSamePath =
1054 aliasObj.alias.split(".")[0] === shortcutAlias.alias.split(".")[0]
1055
1056 if (!isSamePath) {
1057 return
1058 }
1059
1060 shortcutAliases.push({
1061 alias: shortcutAlias.alias,
1062 shortCutOf: aliasObj.alias,
1063 isList: parentEntity.isList ?? true,
1064 isInverse: shortcutAlias.isInverse,
1065 })
1066 })
1067 })
1068
1069 // Only add shortcut aliases if they don’t duplicate existing paths
1070 for (const shortcut of shortcutAliases) {
1071 if (!aliases.some((a) => a.alias === shortcut?.alias)) {
1072 aliases.push(shortcut!)
1073 }
1074 }
1075 }
1076 }
1077
1078 // Add the current entity's alias, avoiding duplication
1079 const pathSegments = parentPath ? parentPath.split(".") : []
1080 const baseAlias =
1081 pathSegments.length && pathSegments[0] === current.alias
1082 ? parentPath // If parentPath already starts with this alias, use it as-is
1083 : `${current.alias}${parentPath ? `.${parentPath}` : ""}`
1084
1085 if (!aliases.some((a) => a.alias === baseAlias)) {
1086 aliases.push({
1087 alias: baseAlias,
1088 isInverse: false,
1089 })
1090 }
1091
1092 pathStack.pop()
1093 visited.delete(current.entity)
1094
1095 return aliases
1096 }
1097
1098 for (const objectRepresentationKey of Object.keys(
1099 objectRepresentation
1100 ).filter(
1101 (key) => !schemaObjectRepresentationPropertiesToOmit.includes(key)
1102 )) {
1103 const entityRepresentationRef =
1104 objectRepresentation[objectRepresentationKey]
1105 const aliases = recursivelyBuildAliasPath(entityRepresentationRef)
1106
1107 for (const alias of aliases) {
1108 if (aliasMap[alias.alias] && !alias.shortCutOf) {
1109 continue
1110 }
1111
1112 aliasMap[alias.alias] = {
1113 ref: entityRepresentationRef,
1114 shortCutOf: alias.shortCutOf,
1115 isList: alias.isList,
1116 isInverse: alias.isInverse,
1117 }
1118 }
1119 }
1120
1121 return aliasMap
1122 }
1123
1124 function buildSchemaFromFilterableLinks(
1125 moduleJoinerConfigs: ModuleJoinerConfig[],
1126 servicesEntityMap: Record<string, any>
1127 ): string {
1128 const allFilterable = moduleJoinerConfigs.flatMap((config) => {
1129 const entities: any[] = []
1130
1131 const schema = config.schema
1132
1133 if (config.isLink) {
1134 if (!config.relationships?.some((r) => r.filterable?.length)) {
1135 return []
1136 }
1137
1138 for (const relationship of config.relationships) {
1139 relationship.filterable ??= []
1140 if (
1141 !relationship.filterable?.length ||
1142 !relationship.filterable?.includes("id")
1143 ) {
1144 relationship.filterable.push("id")
1145 }
1146
1147 const fieldAliasMap: Record<string, string[]> = {}
1148 for (const extend of config.extends ?? []) {
1149 fieldAliasMap[extend.serviceName] = Object.keys(
1150 extend.fieldAlias ?? {}
1151 )
1152 fieldAliasMap[extend.serviceName].push(extend.relationship.alias)
1153 }
1154
1155 const serviceName = relationship.serviceName
1156 entities.push({
1157 serviceName,
1158 entity: relationship.entity,
1159 fields: Array.from(
1160 new Set(
1161 relationship.filterable.concat(fieldAliasMap[serviceName] ?? [])
1162 )
1163 ),
1164 schema,
1165 })
1166 }
1167
1168 return entities
1169 }
1170
1171 let aliases = config.alias ?? []
1172 aliases = (Array.isArray(aliases) ? aliases : [aliases]).filter(
1173 (a) => a.filterable?.length && a.entity
1174 )
1175
1176 for (const alias of aliases) {
1177 entities.push({
1178 serviceName: config.serviceName,
1179 entity: alias.entity,
1180 fields: Array.from(new Set(alias.filterable)),
1181 schema,
1182 })
1183 }
1184 return entities
1185 })
1186
1187 const getGqlType = (entity, field) => {
1188 const fieldRef = (servicesEntityMap[entity] as any)?._fields?.[field]
1189
1190 if (!fieldRef) {
1191 return
1192 }
1193
1194 const fieldType = fieldRef.type.toString()
1195 const isArray = fieldType.startsWith("[")
1196 let currentType = fieldType.replace(/\[|\]|\!/g, "")
1197 const isEnum =
1198 fieldRef.type?.ofType?.astNode?.kind ===
1199 GraphQLUtils.Kind.ENUM_TYPE_DEFINITION
1200
1201 if (isEnum) {
1202 currentType = "String"
1203 }
1204
1205 return isArray ? `[${currentType}]` : currentType
1206 }
1207
1208 const schema = allFilterable
1209 .map(({ serviceName, entity, fields, schema }) => {
1210 if (!schema) {
1211 return
1212 }
1213
1214 const normalizedEntity = lowerCaseFirst(kebabCase(entity))
1215 const events = `@Listeners(values: ["${serviceName}.${normalizedEntity}.created", "${serviceName}.${normalizedEntity}.updated", "${serviceName}.${normalizedEntity}.deleted", "${serviceName}.${normalizedEntity}.restored"])`
1216
1217 const fieldDefinitions = fields
1218 .map((field) => {
1219 const type = getGqlType(entity, field) ?? "String"
1220
1221 return ` ${field}: ${type}`
1222 })
1223 .join("\n")
1224
1225 return `
1226 type ${entity} ${events} {
1227 id: ID!
1228 }
1229
1230 extend type ${entity} {
1231 ${fieldDefinitions}
1232 }`
1233 })
1234 .join("\n\n")
1235
1236 return schema
1237 }
1238
1239 /**
1240 * This util build an internal representation object from the provided schema.
1241 * It will resolve all modules, fields, link module representation to build
1242 * the appropriate representation for the index module.
1243 *
1244 * This representation will be used to re construct the expected output object from a search
1245 * but can also be used for anything since the relation tree is available through ref.
1246 *
1247 * @param schema
1248 */
1249 export function buildSchemaObjectRepresentation(schema: string): {
1250 objectRepresentation: IndexTypes.SchemaObjectRepresentation
1251 entitiesMap: Record<string, any>
1252 executableSchema: GraphQLUtils.GraphQLSchema
1253 } {
1254 const moduleJoinerConfigs = MedusaModule.getAllJoinerConfigs()
1255
1256 const servicesEntityMap = getServicesEntityMap(moduleJoinerConfigs)
1257 const filterableEntities = buildSchemaFromFilterableLinks(
1258 moduleJoinerConfigs,
1259 servicesEntityMap
1260 )
1261
1262 const augmentedSchema =
1263 CustomDirectives.Listeners.definition +
1264 "\n" +
1265 schema +
1266 "\n" +
1267 filterableEntities
1268
1269 const executableSchema = makeSchemaExecutable(augmentedSchema)!
1270 const entitiesMap = executableSchema.getTypeMap()
1271
1272 const objectRepresentation = {
1273 _serviceNameModuleConfigMap: {},
1274 } as IndexTypes.SchemaObjectRepresentation
1275
1276 Object.entries(entitiesMap).forEach(([entityName, entityMapValue]) => {
1277 if (
1278 !entityMapValue.astNode ||
1279 entityMapValue.astNode.kind === GraphQLUtils.Kind.SCALAR_TYPE_DEFINITION
1280 ) {
1281 return
1282 }
1283
1284 processEntity(entityName, {
1285 entitiesMap,
1286 servicesEntityMap,
1287 moduleJoinerConfigs,
1288 objectRepresentationRef: objectRepresentation,
1289 })
1290 })
1291
1292 objectRepresentation._schemaPropertiesMap =
1293 buildAliasMap(objectRepresentation)
1294
1295 return {
1296 objectRepresentation,
1297 entitiesMap,
1298 executableSchema,
1299 }
1300 }