1 import {
2 ModuleJoinerConfig,
3 RemoteJoinerOptions,
4 RemoteJoinerQuery,
5 } from "@medusajs/types"
6 import { MedusaError } from "@medusajs/utils"
7 import { GraphCatalog } from "./catalog"
8 import { compileQuery } from "./compile"
9 import { executePlan } from "./execute"
10 import { IRemoteDataFetcher, RelationMap } from "./types"
11
12 export type { RelationMap } from "./types"
13
14 /**
15 * Executes cross-module graph queries by resolving relationships from module
16 * joiner configs.
17 *
18 * Pipeline: {@link GraphCatalog} (index configs) → {@link compileQuery}
19 * (query → plan) → {@link executePlan} (fetch + join + shortcuts).
20 *
21 * Data loading is delegated to {@link IRemoteDataFetcher} (typically
22 * ModuleDataFetcher). Query is the public entry point that normalizes user
23 * input and invokes {@link RemoteJoiner.query}.
24 */
25 export class RemoteJoiner {
26 private catalog: GraphCatalog
27
28 constructor(
29 serviceConfigs: ModuleJoinerConfig[],
30 private dataFetcher: IRemoteDataFetcher,
31 options: {
32 autoCreateServiceNameAlias?: boolean
33 relationMap?: RelationMap
34 } = {}
35 ) {
36 this.catalog = new GraphCatalog(serviceConfigs, options)
37 }
38
39 async query(
40 queryObj: RemoteJoinerQuery,
41 options?: RemoteJoinerOptions
42 ): Promise<any> {
43 const serviceConfig = this.catalog.getServiceConfig({
44 serviceName: queryObj.service,
45 serviceAlias: queryObj.alias,
46 })
47
48 if (!serviceConfig) {
49 if (queryObj.alias) {
50 throw new Error(`Service with alias "${queryObj.alias}" was not found.`)
51 }
52 throw new Error(`Service "${queryObj.service}" was not found.`)
53 }
54
55 const initialData = options?.initialData
56 ? Array.isArray(options.initialData)
57 ? options.initialData
58 : [options.initialData]
59 : []
60
61 const plan = compileQuery(
62 {
63 query: queryObj,
64 serviceConfig,
65 options,
66 initialData,
67 },
68 this.catalog
69 )
70
71 if (options?.throwIfKeyNotFound) {
72 if (plan.primaryKeyArg?.value == undefined) {
73 if (!plan.primaryKeyArg) {
74 throw new MedusaError(
75 MedusaError.Types.NOT_FOUND,
76 `${
77 serviceConfig.entity ?? serviceConfig.serviceName
78 }: Primary key(s) [${serviceConfig.primaryKeys.join(
79 ", "
80 )}] not found in filters`
81 )
82 }
83
84 throw new MedusaError(
85 MedusaError.Types.NOT_FOUND,
86 `${
87 serviceConfig.entity ?? serviceConfig.serviceName
88 }: Value for primary key ${plan.primaryKeyArg.name} not found in filters`
89 )
90 }
91 }
92
93 const { data, responsePath, rawResponse, wasArray } = await executePlan({
94 plan,
95 dataFetcher: this.dataFetcher,
96 catalog: this.catalog,
97 })
98
99 const retData = wasArray ? data : data[0]
100 if (responsePath) {
101 rawResponse.data[responsePath] = retData
102 } else {
103 rawResponse.data = retData
104 }
105
106 return rawResponse.data
107 }
108 }