1 import {
2 IDmlEntity,
3 JoinerServiceConfigAlias,
4 ModuleJoinerConfig,
5 PropertyType,
6 } from "@medusajs/types"
7 import { accessSync } from "fs"
8 import * as path from "path"
9 import { dirname, join, normalize } from "path"
10 import {
11 camelToSnakeCase,
12 deduplicate,
13 getCallerFilePath,
14 isObject,
15 lowerCaseFirst,
16 MapToConfig,
17 pluralize,
18 toCamelCase,
19 upperCaseFirst,
20 } from "../common"
21 import { DmlEntity, IdProperty, parseEntityName } from "../dml"
22 import { toGraphQLSchema } from "../dml/helpers/create-graphql"
23 import { PrimaryKeyModifier } from "../dml/properties/primary-key"
24 import { BaseRelationship } from "../dml/relations/base"
25 import { BelongsTo } from "../dml/relations/belongs-to"
26 import { loadModels } from "./loaders/load-models"
27 import { InferLinkableKeys, InfersLinksConfig } from "./types/links-config"
28
29 /**
30 * Define joiner config for a module based on the models (object representation or entities) present in the models directory. This action will be sync until
31 * we move to at least es2022 to have access to top-leve await.
32 *
33 * The aliases will be built from the entityQueryingConfig and custom aliases if provided, in case of aliases provided if the methodSuffix is not provided
34 * then it will be inferred from the entity name of the alias args.
35 *
36 * @param serviceName
37 * @param alias custom aliases will be merged with the computed aliases from the provided models. Though, if a custom alias correspond to a computed alias for the same model then the custom alias will take place. Also, note that the methodSuffix will be inferred from the entity name if not provided as part of the args.
38 * @param schema
39 * @param models
40 * @param linkableKeys
41 * @param primaryKeys
42 */
43 export function defineJoinerConfig(
44 serviceName: string,
45 {
46 alias,
47 schema,
48 models,
49 linkableKeys,
50 primaryKeys,
51 idPrefixToEntityName,
52 }: {
53 alias?: JoinerServiceConfigAlias[]
54 idPrefixToEntityName?: Record<string, string>
55 schema?: string
56 models?: DmlEntity<any, any>[] | { name: string }[]
57 linkableKeys?: ModuleJoinerConfig["linkableKeys"]
58 primaryKeys?: string[]
59 } = {}
60 ): Omit<
61 ModuleJoinerConfig,
62 "serviceName" | "primaryKeys" | "linkableKeys" | "alias"
63 > &
64 Required<
65 Pick<
66 ModuleJoinerConfig,
67 "serviceName" | "primaryKeys" | "linkableKeys" | "alias"
68 >
69 > {
70 let loadedModels = models
71
72 if (!loadedModels) {
73 loadedModels = []
74
75 let index = 1
76
77 while (true) {
78 ++index
79 let fullPath = getCallerFilePath(index)
80 if (!fullPath) {
81 break
82 }
83
84 fullPath = normalize(fullPath)
85 const integrationTestPotentialPath = normalize(
86 "integration-tests/__tests__"
87 )
88
89 /**
90 * Handle integration-tests/__tests__ path based on conventional naming
91 */
92 if (fullPath.includes(integrationTestPotentialPath)) {
93 const sourcePath = fullPath.split(integrationTestPotentialPath)[0]
94 fullPath = path.join(sourcePath, "src")
95 }
96
97 const srcDir = fullPath.includes("dist") ? "dist" : "src"
98 const splitPath = fullPath.split(srcDir)
99
100 let basePath = splitPath[0] + srcDir
101
102 const potentialModulesDirPathSegment = normalize(`${srcDir}/modules/`)
103 const isMedusaProject = fullPath.includes(potentialModulesDirPathSegment)
104 if (isMedusaProject) {
105 basePath = dirname(fullPath)
106 }
107
108 basePath = join(basePath, "models")
109 let doesModelsDirExist = false
110 try {
111 accessSync(path.resolve(basePath))
112 doesModelsDirExist = true
113 } catch (e) {}
114
115 if (!doesModelsDirExist) {
116 continue
117 }
118
119 loadedModels = loadModels(basePath)
120
121 if (loadedModels.length) {
122 break
123 }
124 }
125 }
126
127 const modelDefinitions = new Map<string, DmlEntity<any, any>>(
128 loadedModels!
129 .filter(
130 (model): model is DmlEntity<any, any> => !!DmlEntity.isDmlEntity(model)
131 )
132 .map((model) => [model.name, model])
133 )
134 const mikroOrmObjects = new Map<string, Function>(
135 loadedModels!
136 .filter((model): model is Function => !DmlEntity.isDmlEntity(model))
137 .map((model) => [model.name, model])
138 )
139
140 // We prioritize DML if there is any equivalent Mikro orm entities found
141 const deduplicatedLoadedModels = [...modelDefinitions.values()] as (
142 | DmlEntity<any, any>
143 | { name: string }
144 )[]
145 mikroOrmObjects.forEach((model) => {
146 if (modelDefinitions.has(model.name)) {
147 return
148 }
149
150 deduplicatedLoadedModels.push(model)
151 })
152
153 if (!schema) {
154 schema = toGraphQLSchema([...modelDefinitions.values()])
155 }
156
157 if (!idPrefixToEntityName) {
158 idPrefixToEntityName = buildIdPrefixToEntityNameFromDmlObjects([
159 ...modelDefinitions.values(),
160 ])
161 }
162
163 const linkableKeysFromDml = buildLinkableKeysFromDmlObjects([
164 ...modelDefinitions.values(),
165 ])
166 const linkableKeysFromMikroOrm = buildLinkableKeysFromMikroOrmObjects([
167 ...mikroOrmObjects.values(),
168 ])
169
170 const mergedLinkableKeys = {
171 ...linkableKeysFromDml,
172 ...linkableKeysFromMikroOrm,
173 ...linkableKeys,
174 }
175 linkableKeys = mergedLinkableKeys
176
177 /**
178 * Merge custom primary keys from the joiner config with the infered primary keys
179 * from the models.
180 *
181 * TODO: Maybe worth looking into the real needs for primary keys.
182 * It can happen that we could just remove that but we need to investigate (looking at the
183 * lookups from the remote joiner to identify which entity a property refers to)
184 */
185 primaryKeys ??= []
186 const finalPrimaryKeys = new Set(primaryKeys)
187 if (modelDefinitions.size) {
188 const linkConfig = buildLinkConfigFromModelObjects(
189 serviceName,
190 Object.fromEntries(modelDefinitions)
191 )
192
193 Object.values(linkConfig).flatMap((entityLinkConfig) => {
194 return Object.values(
195 entityLinkConfig as Record<string, { primaryKey: string }>
196 )
197 .filter((linkableConfig) => isObject(linkableConfig))
198 .forEach((linkableConfig) => {
199 finalPrimaryKeys.add(linkableConfig.primaryKey)
200 })
201 })
202 }
203
204 primaryKeys = Array.from(finalPrimaryKeys.add("id"))
205
206 const crossModuleJoinMetadataByEntity =
207 buildCrossModuleJoinMetadataFromDmlObjects(
208 Array.from(modelDefinitions.values())
209 )
210
211 // TODO: In the context of DML add a validation on primary keys and linkable keys if the consumer provide them manually. follow up pr
212
213 return {
214 serviceName,
215 primaryKeys,
216 schema,
217 idPrefixToEntityName,
218 linkableKeys: linkableKeys,
219 alias: [
220 ...(alias ?? ([] as any)).map((aliasConfig) => ({
221 name: aliasConfig.name,
222 entity: aliasConfig.entity,
223 filterable: aliasConfig.filterable,
224 ...(crossModuleJoinMetadataByEntity[aliasConfig.entity]
225 ? {
226 __internal: crossModuleJoinMetadataByEntity[aliasConfig.entity],
227 }
228 : {}),
229 args: {
230 methodSuffix:
231 aliasConfig.args?.methodSuffix ??
232 pluralize(upperCaseFirst(aliasConfig.entity)),
233 },
234 })),
235 ...deduplicatedLoadedModels
236 .filter((model) => {
237 return (
238 !alias ||
239 !alias.some((alias) => alias.entity === upperCaseFirst(model.name))
240 )
241 })
242 .map((entity) => {
243 const entityName = upperCaseFirst(entity.name)
244 const crossModuleJoinMetadata =
245 crossModuleJoinMetadataByEntity[entityName]
246
247 return {
248 name: [
249 `${camelToSnakeCase(entity.name).toLowerCase()}`,
250 `${pluralize(camelToSnakeCase(entity.name).toLowerCase())}`,
251 ],
252 entity: entityName,
253 ...(crossModuleJoinMetadata
254 ? {
255 __internal: crossModuleJoinMetadata,
256 }
257 : {}),
258 args: {
259 methodSuffix: pluralize(entityName),
260 },
261 }
262 }),
263 ],
264 }
265 }
266
267 type CrossModuleJoinAliasMetadata = NonNullable<
268 JoinerServiceConfigAlias["__internal"]
269 >
270
271 type InternalRelationMetadata = NonNullable<
272 CrossModuleJoinAliasMetadata["relations"]
273 >[string]
274
275 /**
276 * Build cross-module join metadata from DML entity definitions.
277 * Crossjoinable fields are all non-computed DML properties, and relations
278 * describe how module-internal DML relations join at the SQL level. Together
279 * with the physical table name they determine what optimizations for
280 * cross-module joins can be performed.
281 */
282 function buildCrossModuleJoinMetadataFromDmlObjects(
283 models: DmlEntity<any, any>[]
284 ): Record<string, CrossModuleJoinAliasMetadata> {
285 const metadata: Record<string, CrossModuleJoinAliasMetadata> = {}
286
287 for (const model of models) {
288 if (!DmlEntity.isDmlEntity(model)) {
289 continue
290 }
291
292 const entityName = upperCaseFirst(model.name)
293 const { tableNameWithoutSchema, pgSchema } = parseEntityName(model)
294
295 const crossjoinable: string[] = []
296 const relations: Record<string, InternalRelationMetadata> = {}
297
298 for (const [property, value] of Object.entries(model.schema)) {
299 if (BaseRelationship.isRelationship(value)) {
300 const relationMetadata = deriveInternalRelationMetadata(
301 model,
302 property,
303 value
304 )
305
306 if (relationMetadata) {
307 relations[property] = relationMetadata
308
309 // belongsTo foreign keys are real columns on this table (e.g.
310 // price.price_list_id) and are filterable like any other column.
311 if (relationMetadata.foreignKeyOwner === "self") {
312 crossjoinable.push(relationMetadata.foreignKey)
313 }
314 }
315 continue
316 }
317
318 const parsedProperty = (value as PropertyType<any>).parse(property)
319
320 if (parsedProperty.computed) {
321 continue
322 }
323
324 crossjoinable.push(property)
325 }
326
327 metadata[entityName] = {
328 crossjoinable: deduplicate(crossjoinable),
329 tableName: tableNameWithoutSchema,
330 ...(pgSchema ? { schema: pgSchema } : {}),
331 ...(Object.keys(relations).length ? { relations } : {}),
332 }
333 }
334
335 return metadata
336 }
337
338 /**
339 * Derive the SQL join shape of a module-internal DML relation. Only hasMany
340 * and belongsTo have a statically known join column; other relation kinds
341 * (hasOne, manyToMany) are skipped and stay untraversable for cross-module
342 * SQL joins.
343 */
344 function deriveInternalRelationMetadata(
345 model: DmlEntity<any, any>,
346 property: string,
347 relationship: unknown
348 ): InternalRelationMetadata | undefined {
349 const parsed = (
350 relationship as { parse: (name: string) => Record<string, any> }
351 ).parse(property)
352
353 const referenced =
354 typeof parsed.entity === "function" ? parsed.entity() : parsed.entity
355
356 if (!DmlEntity.isDmlEntity(referenced)) {
357 return undefined
358 }
359
360 const relatedEntityName = upperCaseFirst(referenced.name)
361
362 if (parsed.type === "belongsTo") {
363 const foreignKey =
364 parsed.options?.foreignKeyName ?? camelToSnakeCase(`${property}Id`)
365
366 return {
367 entity: relatedEntityName,
368 foreignKey,
369 foreignKeyOwner: "self",
370 }
371 }
372
373 if (parsed.type === "hasMany") {
374 // The join column lives on the related model, defined by its belongsTo
375 // inverse (mirrors defineRelationship's OneToMany mapping).
376 const mappedBy =
377 parsed.mappedBy ??
378 camelToSnakeCase(upperCaseFirst(toCamelCase(model.name)))
379
380 const inverse = referenced.schema[mappedBy]
381 if (!inverse || !BelongsTo.isBelongsTo(inverse)) {
382 return undefined
383 }
384
385 const inverseParsed = (
386 inverse as unknown as { parse: (name: string) => Record<string, any> }
387 ).parse(mappedBy)
388 const foreignKey =
389 inverseParsed.options?.foreignKeyName ??
390 camelToSnakeCase(`${mappedBy}Id`)
391
392 return {
393 entity: relatedEntityName,
394 foreignKey,
395 foreignKeyOwner: "target",
396 isList: true,
397 }
398 }
399
400 return undefined
401 }
402
403 /**
404 * Build the id prefix to entity name map from the DML objects
405 * @param models
406 */
407 export function buildIdPrefixToEntityNameFromDmlObjects(
408 models: DmlEntity<any, any>[]
409 ): Record<string, string> {
410 return models.reduce((acc, model) => {
411 const id = model.parse().schema.id as
412 | IdProperty
413 | PrimaryKeyModifier<any, any>
414
415 if (
416 PrimaryKeyModifier.isPrimaryKeyModifier(id) &&
417 id.schema.dataType.options.prefix
418 ) {
419 acc[id.schema.dataType.options.prefix] = model.name
420 } else if (IdProperty.isIdProperty(id) && id.dataType.options.prefix) {
421 acc[id.dataType.options.prefix] = model.name
422 }
423
424 return acc
425 }, {})
426 }
427
428 /**
429 * From a set of DML objects, build the linkable keys
430 *
431 * @example
432 * const user = model.define("user", {
433 * id: model.id(),
434 * name: model.text(),
435 * })
436 *
437 * const car = model.define("car", {
438 * id: model.id(),
439 * number_plate: model.text().primaryKey(),
440 * test: model.text(),
441 * })
442 *
443 * const linkableKeys = buildLinkableKeysFromDmlObjects([user, car])
444 *
445 * // output:
446 * // {
447 * // user_id: 'User',
448 * // car_number_plate: 'Car',
449 * // }
450 *
451 * @param models
452 */
453 export function buildLinkableKeysFromDmlObjects<
454 const T extends DmlEntity<any, any>[],
455 LinkableKeys = InferLinkableKeys<T>
456 >(models: T): LinkableKeys {
457 const linkableKeys = {} as LinkableKeys
458
459 for (const model of models) {
460 if (!DmlEntity.isDmlEntity(model)) {
461 continue
462 }
463
464 const schema = model.schema
465 const primaryKeys: string[] = []
466
467 for (const [property, value] of Object.entries(schema)) {
468 if (BaseRelationship.isRelationship(value)) {
469 continue
470 }
471
472 const parsedProperty = (value as PropertyType<any>).parse(property)
473 if (PrimaryKeyModifier.isPrimaryKeyModifier(value)) {
474 const linkableKeyName =
475 parsedProperty.dataType.options?.linkable ??
476 `${camelToSnakeCase(model.name).toLowerCase()}_${property}`
477 primaryKeys.push(linkableKeyName)
478 }
479 }
480
481 if (primaryKeys.length) {
482 primaryKeys.forEach((primaryKey) => {
483 linkableKeys[primaryKey] = upperCaseFirst(model.name)
484 })
485 }
486 }
487
488 return linkableKeys
489 }
490
491 /**
492 * Build linkable keys from MikroORM objects
493 * @deprecated
494 * @param models
495 */
496 export function buildLinkableKeysFromMikroOrmObjects(
497 models: Function[]
498 ): Record<string, string> {
499 return models.reduce((acc, entity) => {
500 acc[`${camelToSnakeCase(entity.name).toLowerCase()}_id`] = entity.name
501 return acc
502 }, {}) as Record<string, string>
503 }
504
505 /**
506 * Build entities name to linkable keys map
507 *
508 * @example
509 * const user = model.define("user", {
510 * id: model.id(),
511 * name: model.text(),
512 * })
513 *
514 * const car = model.define("car", {
515 * id: model.id(),
516 * number_plate: model.text().primaryKey(),
517 * test: model.text(),
518 * })
519 *
520 * const links = buildLinkConfigFromModelObjects('userService', { user, car })
521 *
522 * // output:
523 * // {
524 * // user: {
525 * // id: {
526 * // serviceName: 'userService', // The name of the module service it originate from
527 * // field: 'user', // The field name of the entity, the query field is inferred from it as kebab cased singular/plural
528 * // linkable: 'user_id', // The linkable key
529 * // primaryKey: 'id' // The primary key if refers to in the original object representation, it will be used to be passed to the filters of the corresponding public service method
530 * // },
531 * // toJSON() { ... }
532 * // },
533 * // car: {
534 * // number_plate: {
535 * // serviceName: 'userService',
536 * // field: 'car',
537 * // linkable: 'car_number_plate',
538 * // primaryKey: 'number_plate'
539 * // },
540 * // toJSON() { ... }
541 * // }
542 * // }
543 *
544 * @param serviceName
545 * @param models
546 */
547 export function buildLinkConfigFromModelObjects<
548 const ServiceName extends string,
549 const T extends Record<string, IDmlEntity<any, any>>
550 >(
551 serviceName: ServiceName,
552 models: T,
553 linkableKeys: Record<string, string> = {}
554 ): InfersLinksConfig<ServiceName, T> {
555 // In case some models have been provided to a custom joiner config, the linkable will be limited
556 // to that set of models. We dont want to expose models that should not be linkable.
557 const linkableModels = Object.values(linkableKeys)
558 const linkConfig = {} as InfersLinksConfig<ServiceName, T>
559
560 for (const model of Object.values(models) ?? []) {
561 const classLikeModelName = upperCaseFirst(model.name)
562
563 if (
564 !DmlEntity.isDmlEntity(model) ||
565 (linkableModels.length && !linkableModels.includes(classLikeModelName))
566 ) {
567 continue
568 }
569
570 const schema = model.schema
571
572 /**
573 * When using a linkable, if a specific linkable property is not specified, the toJSON
574 * function will be called and return the first linkable available for this model.
575 */
576 const modelLinkConfig = (linkConfig[lowerCaseFirst(model.name)] ??= {
577 toJSON: function () {
578 const linkables = Object.entries(this)
579 .filter(([name]) => name !== "toJSON")
580 .map(([, object]) => object)
581 return linkables[0]
582 },
583 })
584
585 /**
586 * Build all linkable properties for the model
587 */
588 for (const [property, value] of Object.entries(schema)) {
589 if (BaseRelationship.isRelationship(value)) {
590 continue
591 }
592
593 const parsedProperty = (value as PropertyType<any>).parse(property)
594 if (
595 PrimaryKeyModifier.isPrimaryKeyModifier(value) ||
596 IdProperty.isIdProperty(value)
597 ) {
598 const linkableKeyName =
599 parsedProperty.dataType.options?.linkable ??
600 `${camelToSnakeCase(model.name).toLowerCase()}_${property}`
601
602 modelLinkConfig[property] = {
603 linkable: linkableKeyName,
604 primaryKey: property,
605 serviceName,
606 field: lowerCaseFirst(model.name),
607 entity: classLikeModelName,
608 }
609 }
610 }
611 }
612
613 /**
614 * If the joiner config specify some custom linkable keys, we merge them with the
615 * existing linkable keys infered from the model above.
616 */
617 for (const [linkableKey, modelName] of Object.entries(linkableKeys) ?? []) {
618 const snakeCasedModelName = camelToSnakeCase(toCamelCase(modelName))
619
620 // Linkable keys by default are prepared with snake cased model name _id
621 // So to be able to compare only the property we have to remove the first part
622 const inferredReferenceProperty = linkableKey.replace(
623 `${snakeCasedModelName}_`,
624 ""
625 )
626
627 linkConfig[lowerCaseFirst(modelName)] ??= {
628 toJSON: function () {
629 const linkables = Object.entries(this)
630 .filter(([name]) => name !== "toJSON")
631 .map(([, object]) => object)
632 return linkables[0]
633 },
634 }
635
636 if (linkConfig[lowerCaseFirst(modelName)][inferredReferenceProperty]) {
637 continue
638 }
639
640 linkConfig[lowerCaseFirst(modelName)][inferredReferenceProperty] = {
641 linkable: linkableKey,
642 primaryKey: inferredReferenceProperty,
643 serviceName,
644 field: lowerCaseFirst(modelName),
645 entity: upperCaseFirst(modelName),
646 }
647 }
648
649 return linkConfig as InfersLinksConfig<ServiceName, T>
650 }
651
652 /**
653 * @deprecated temporary supports for mikro orm entities to get the linkable available from the module export while waiting for the migration to DML
654 *
655 * @param serviceName
656 * @param linkableKeys
657 */
658 export function buildLinkConfigFromLinkableKeys<
659 const ServiceName extends string,
660 const T extends Record<string, string>
661 >(serviceName: ServiceName, linkableKeys: T): Record<string, any> {
662 const linkConfig = {} as Record<string, any>
663
664 for (const [linkable, modelName] of Object.entries(linkableKeys)) {
665 const kebabCasedModelName = camelToSnakeCase(toCamelCase(modelName))
666
667 const inferredReferenceProperty = linkable.replace(
668 `${kebabCasedModelName}_`,
669 ""
670 )
671
672 const keyName = lowerCaseFirst(modelName)
673 const config = {
674 linkable: linkable,
675 primaryKey: inferredReferenceProperty,
676 serviceName,
677 field: keyName,
678 entity: upperCaseFirst(modelName),
679 }
680
681 linkConfig[keyName] ??= {
682 toJSON: () => config,
683 }
684 linkConfig[keyName][inferredReferenceProperty] = config
685 }
686
687 return linkConfig as Record<string, any>
688 }
689
690 /**
691 * Reversed map from linkableKeys to entity name to linkable keys
692 * @param linkableKeys
693 */
694 export function buildModelsNameToLinkableKeysMap(
695 linkableKeys: Record<string, string>
696 ): MapToConfig {
697 const entityLinkableKeysMap: MapToConfig = {}
698 Object.entries(linkableKeys).forEach(([key, value]) => {
699 entityLinkableKeysMap[value] ??= []
700 entityLinkableKeysMap[value].push({
701 mapTo: key,
702 valueFrom: key.split("_").pop()!,
703 })
704 })
705 return entityLinkableKeysMap
706 }