1 import { JoinerRelationship, RemoteJoinerOptions } from "@medusajs/types"
2 import {
3 FilterOperatorMap,
4 isDefined,
5 isObject,
6 MedusaError,
7 } from "@medusajs/utils"
8 import { GraphCatalog } from "./catalog"
9 import {
10 applyResidualFilters,
11 hideResidualProperties,
12 } from "./cross-module-joins/residual-filters"
13 import { sortByResidualOrder } from "./cross-module-joins/residual-order"
14 import { getNestedItems } from "./helpers"
15 import {
16 BASE_PATH,
17 ComputedJoinerRelationship,
18 InternalJoinerServiceConfig,
19 IRemoteDataFetcher,
20 QueryPlan,
21 RemoteExpandProperty,
22 RemoteNestedExpands,
23 ShortcutSpec,
24 } from "./types"
25
26 type PathCtx = {
27 path: string
28 expand: RemoteExpandProperty
29 relationship: ComputedJoinerRelationship
30 nestedItems: any[]
31 field: string
32 fieldsArray: string[]
33 ids: Set<any>
34 }
35
36 /**
37 * Executes a compiled {@link QueryPlan}: fetch root, merge seed data, walk
38 * depth stages fetching related rows and joining them onto parents, then
39 * collapse fieldAlias shortcuts.
40 */
41
42 export async function executePlan({
43 plan,
44 dataFetcher,
45 catalog,
46 }: {
47 plan: QueryPlan
48 dataFetcher: IRemoteDataFetcher
49 catalog: GraphCatalog
50 }): Promise<{
51 data: any
52 responsePath?: string
53 rawResponse: {
54 data: unknown[] | { [path: string]: unknown }
55 path?: string
56 }
57 wasArray: boolean
58 }> {
59 const { options } = plan
60
61 const residuals = plan.residualCrossModuleFilters ?? []
62 const residualOrderBy = plan.residualOrderBy ?? []
63 const hasResiduals = residuals.length > 0 || residualOrderBy.length > 0
64 // Residuals are completed in memory below, so pagination moves with them:
65 // pull it off the root fetch and re-apply after filtering/sorting.
66 const pagination = hasResiduals
67 ? extractRootPagination(plan.root)
68 : undefined
69
70 const response = await fetchData({
71 dataFetcher,
72 expand: plan.root,
73 pkField: plan.pkName,
74 ids: plan.primaryKeyArg?.value,
75 options,
76 })
77
78 let data = response.path ? response.data[response.path!] : response.data
79 const wasArray = Array.isArray(data)
80 data = wasArray ? data : [data]
81
82 if (options?.initialData) {
83 data = mergeInitialData({
84 items: data,
85 initialData: plan.initialData,
86 serviceConfig: plan.root.serviceConfig,
87 expands: plan.expands.get(BASE_PATH)?.expands,
88 relationship: plan.root.serviceConfig.relationships?.get(
89 plan.root.serviceConfig.serviceName
90 ) as JoinerRelationship | undefined,
91 catalog,
92 })
93 delete options.initialData
94 }
95
96 await handleExpands({
97 items: data,
98 plan,
99 dataFetcher,
100 catalog,
101 })
102
103 if (hasResiduals) {
104 if (residuals.length) {
105 data = applyResidualFilters({ items: data, residuals })
106 }
107
108 if (residualOrderBy.length) {
109 sortByResidualOrder({ items: data, orderBy: residualOrderBy })
110 }
111
112 if (plan.residualHiddenProperties?.length) {
113 hideResidualProperties({
114 items: data,
115 hidden: plan.residualHiddenProperties,
116 })
117 }
118
119 const count = data.length
120
121 if (pagination) {
122 const skip = pagination.skip ?? 0
123 data =
124 pagination.take != null
125 ? data.slice(skip, skip + pagination.take)
126 : skip
127 ? data.slice(skip)
128 : data
129
130 if (pagination.withMetadata) {
131 return {
132 data,
133 responsePath: "rows",
134 rawResponse: {
135 data: {
136 rows: data,
137 metadata: {
138 skip: pagination.skip,
139 take: pagination.take,
140 count,
141 },
142 },
143 path: "rows",
144 },
145 wasArray,
146 }
147 }
148 }
149 }
150
151 return {
152 data,
153 responsePath: response.path,
154 rawResponse: response,
155 wasArray,
156 }
157 }
158
159 /**
160 * Removes pagination args from the root fetch so residuals evaluate against
161 * the full (stage-1 filtered) root set. `withMetadata` mirrors the data
162 * fetcher's skip/cursor detection, which decides whether the response gets a
163 * `{ rows, metadata }` envelope.
164 */
165 function extractRootPagination(root: RemoteExpandProperty):
166 | {
167 skip?: number
168 take?: number | null
169 withMetadata: boolean
170 }
171 | undefined {
172 if (!root.args?.length) {
173 return undefined
174 }
175
176 const aliases: Record<string, "skip" | "take" | "cursor"> = {
177 skip: "skip",
178 offset: "skip",
179 take: "take",
180 limit: "take",
181 cursor: "cursor",
182 }
183
184 const captured: { skip?: number; take?: number | null } = {}
185 let found = false
186 let withMetadata = false
187
188 root.args = root.args.filter((arg) => {
189 const target = aliases[arg.name]
190 if (!target) {
191 return true
192 }
193
194 found = true
195 if (target === "skip" || target === "cursor") {
196 withMetadata = true
197 }
198 if (target !== "cursor") {
199 captured[target] = arg.value
200 }
201 return false
202 })
203
204 return found ? { ...captured, withMetadata } : undefined
205 }
206
207 /**
208 * Prunes a record to the requested fields, recursively for nested expands.
209 */
210 export function filterFields(
211 data: any,
212 fields?: string[],
213 expands?: RemoteNestedExpands
214 ): Record<string, unknown> | undefined {
215 if (!fields || !data) {
216 return data
217 }
218
219 let filteredData: Record<string, unknown> = {}
220
221 if (fields.includes("*")) {
222 filteredData = data
223 } else {
224 filteredData = fields.reduce((acc: any, field: string) => {
225 const fieldValue = data?.[field]
226 if (isDefined(fieldValue)) {
227 acc[field] = data?.[field]
228 }
229 return acc
230 }, {})
231 }
232
233 if (expands) {
234 for (const key of Object.keys(expands)) {
235 const expand = expands[key]
236 if (!expand) {
237 continue
238 }
239
240 if (Array.isArray(data[key])) {
241 filteredData[key] = data[key].map((item: any) =>
242 filterFields(item, expand.fields, expand.expands)
243 )
244 } else {
245 const filtered = filterFields(data[key], expand.fields, expand.expands)
246 if (isDefined(filtered)) {
247 filteredData[key] = filtered
248 }
249 }
250 }
251 }
252
253 return (Object.keys(filteredData).length && filteredData) || undefined
254 }
255
256 async function fetchData(params: {
257 dataFetcher: IRemoteDataFetcher
258 expand: RemoteExpandProperty
259 pkField: string
260 ids?: (unknown | unknown[])[]
261 relationship?: any
262 options?: RemoteJoinerOptions
263 }): Promise<{
264 data: unknown[] | { [path: string]: unknown }
265 path?: string
266 }> {
267 const { dataFetcher, expand, pkField, ids, relationship, options } = params
268
269 let uniqueIds: unknown[] | undefined
270 if (ids != null) {
271 const isIdsUsingOperatorMap =
272 isObject(ids) && Object.keys(ids).some((key) => !!FilterOperatorMap[key])
273 uniqueIds = isIdsUsingOperatorMap ? ids : Array.isArray(ids) ? ids : [ids]
274 uniqueIds = Array.isArray(uniqueIds)
275 ? uniqueIds.filter((id) => id != null)
276 : uniqueIds
277 }
278
279 if (uniqueIds && Array.isArray(uniqueIds)) {
280 const isCompositeKey = Array.isArray(uniqueIds[0])
281 if (isCompositeKey) {
282 const seen = new Set()
283 uniqueIds = uniqueIds.filter((idArray) => {
284 const key = JSON.stringify(idArray)
285 const isNew = !seen.has(key)
286 seen.add(key)
287 return isNew
288 })
289 } else {
290 uniqueIds = Array.from(new Set(uniqueIds.flat()))
291 }
292 }
293
294 let pkFieldAdjusted = pkField
295 if (relationship) {
296 pkFieldAdjusted = relationship.inverse
297 ? relationship.foreignKey.split(".").pop()!
298 : relationship.primaryKey
299 }
300
301 const response = await dataFetcher.fetch(
302 expand,
303 pkFieldAdjusted,
304 uniqueIds,
305 relationship
306 )
307
308 const isObj = isDefined(response.path)
309 let resData = isObj ? response.data[response.path!] : response.data
310
311 resData = isDefined(resData)
312 ? Array.isArray(resData)
313 ? resData
314 : [resData]
315 : []
316
317 checkIfKeysExist({
318 uniqueIds,
319 resData,
320 expand,
321 pkField: pkFieldAdjusted,
322 relationship,
323 options,
324 })
325
326 const filteredDataArray = resData.map((row: any) =>
327 filterFields(row, expand.fields, expand.expands)
328 )
329
330 if (isObj) {
331 response.data[response.path!] = filteredDataArray
332 } else {
333 response.data = filteredDataArray
334 }
335
336 return response
337 }
338
339 function checkIfKeysExist(params: {
340 uniqueIds: unknown[] | undefined
341 resData: any[]
342 expand: RemoteExpandProperty
343 pkField: string
344 relationship?: any
345 options?: RemoteJoinerOptions
346 }) {
347 const { uniqueIds, resData, expand, pkField, relationship, options } = params
348
349 if (
350 !(
351 isDefined(uniqueIds) &&
352 ((options?.throwIfKeyNotFound && !isDefined(relationship)) ||
353 (options?.throwIfRelationNotFound && isDefined(relationship)))
354 )
355 ) {
356 return
357 }
358
359 if (isDefined(relationship)) {
360 if (
361 Array.isArray(options?.throwIfRelationNotFound) &&
362 !options?.throwIfRelationNotFound.includes(relationship.serviceName)
363 ) {
364 return
365 }
366 }
367
368 const notFound = new Set(uniqueIds)
369 resData.forEach((data) => {
370 notFound.delete(data[pkField])
371 })
372
373 if (notFound.size > 0) {
374 const entityName =
375 expand.serviceConfig.entity ??
376 expand.serviceConfig.args?.methodSuffix ??
377 expand.serviceConfig.serviceName
378
379 throw new MedusaError(
380 MedusaError.Types.NOT_FOUND,
381 `${entityName} ${pkField} not found: ` + Array.from(notFound).join(", ")
382 )
383 }
384 }
385
386 async function handleExpands(params: {
387 items: any[]
388 plan: QueryPlan
389 dataFetcher: IRemoteDataFetcher
390 catalog: GraphCatalog
391 }): Promise<void> {
392 const { items, plan, dataFetcher, catalog } = params
393 const { expands: parsedExpands, shortcuts, options } = plan
394
395 const root = parsedExpands.get(BASE_PATH)!
396 const executionStages = root.executionStages ?? []
397 // Skip root stage (depth 0)
398 const stages = executionStages.slice(1)
399
400 for (const stage of stages) {
401 const stageFetchGroups: {
402 ctxs: PathCtx[]
403 relationship: ComputedJoinerRelationship
404 promise: ReturnType<typeof fetchData>
405 }[] = []
406
407 for (const { paths } of stage) {
408 const pathCtx: PathCtx[] = []
409
410 for (const path of paths) {
411 const expand = parsedExpands.get(path)!
412 const nestedItems = getItemsForPath(items, path)
413
414 if (!nestedItems?.length || !expand) {
415 continue
416 }
417
418 const relationship = catalog.getEntityRelationship({
419 parentServiceConfig: expand.parentConfig!,
420 property: expand.property,
421 entity: expand.entity,
422 })
423
424 if (!relationship) {
425 continue
426 }
427
428 const { field, fieldsArray, idsToFetch } = computeIdsForRelationship(
429 nestedItems,
430 relationship
431 )
432
433 pathCtx.push({
434 path,
435 expand,
436 relationship,
437 nestedItems,
438 field,
439 fieldsArray,
440 ids: idsToFetch,
441 })
442 }
443
444 if (!pathCtx.length) {
445 continue
446 }
447
448 const byPkField = new Map<string, PathCtx[]>()
449 for (const ctx of pathCtx) {
450 if (!byPkField.has(ctx.field)) {
451 byPkField.set(ctx.field, [])
452 }
453 byPkField.get(ctx.field)!.push(ctx)
454 }
455
456 for (const [pkField, ctxs] of byPkField.entries()) {
457 const unionIds: any[] = Array.from(
458 new Set(ctxs.flatMap((c) => Array.from(c.ids)))
459 )
460 const unionFields = Array.from(
461 new Set(ctxs.flatMap((c) => c.expand.fields ?? []))
462 )
463 const unionArgs = ctxs.flatMap((c) => c.expand.args ?? [])
464
465 const base = ctxs[0].expand
466 const aggExpand: RemoteExpandProperty = {
467 ...base,
468 fields: unionFields,
469 }
470 if (unionArgs.length) {
471 aggExpand.args = unionArgs
472 }
473
474 const relationship = ctxs[0].relationship
475 const promise = fetchData({
476 dataFetcher,
477 expand: aggExpand,
478 pkField,
479 ids: unionIds,
480 relationship,
481 options,
482 })
483
484 stageFetchGroups.push({ ctxs, relationship, promise })
485 }
486 }
487
488 const stageResults = await Promise.all(
489 stageFetchGroups.map((g) => g.promise)
490 )
491
492 for (let i = 0; i < stageFetchGroups.length; i++) {
493 const { ctxs, relationship } = stageFetchGroups[i]
494 const relatedDataArray = stageResults[i]
495
496 const joinFields = relationship.inverse
497 ? relationship.foreignKeyArr
498 : relationship.primaryKeyArr
499
500 const relData = relatedDataArray.path
501 ? (relatedDataArray.data as any)[relatedDataArray.path!]
502 : relatedDataArray.data
503
504 const relatedDataMap = createRelatedDataMap(relData, joinFields)
505
506 for (const ctx of ctxs) {
507 assignRelatedToItems({
508 items: ctx.nestedItems,
509 relationship: ctx.relationship,
510 relatedDataMap,
511 field: ctx.field,
512 fieldsArray: ctx.fieldsArray,
513 })
514 }
515 }
516 }
517
518 if (shortcuts.length > 0) {
519 applyShortcuts({
520 items,
521 parsedExpands,
522 shortcuts,
523 })
524 }
525 }
526
527 /**
528 * Post-join result shaping: collapse fieldAlias shortcuts onto their short
529 * names and hide intermediate nodes that existed only for the rewrite.
530 */
531 function applyShortcuts(params: {
532 items: any[]
533 parsedExpands: Map<string, RemoteExpandProperty>
534 shortcuts: ShortcutSpec[]
535 }): void {
536 const { items, parsedExpands, shortcuts } = params
537
538 const getChildren = (item: any, prop: string) => {
539 if (Array.isArray(item)) {
540 return item.flatMap((currentItem) => currentItem[prop])
541 }
542 return item[prop]
543 }
544
545 const removeChildren = (item: any, prop: string) => {
546 if (Array.isArray(item)) {
547 for (let i = 0; i < item.length; i++) {
548 Object.defineProperty(item[i], prop, {
549 value: undefined,
550 enumerable: false,
551 })
552 }
553 } else {
554 Object.defineProperty(item, prop, {
555 value: undefined,
556 enumerable: false,
557 })
558 }
559 }
560
561 const cleanup: [any, string][] = []
562
563 for (const alias of shortcuts) {
564 const propPath = alias.path.slice(alias.location.length)
565
566 let itemsLocation = items
567 for (const locationProp of alias.location) {
568 itemsLocation = getNestedItems(itemsLocation, locationProp)
569 }
570
571 itemsLocation.forEach((locationItem) => {
572 if (!locationItem) {
573 return
574 }
575
576 let currentItems = locationItem
577 let parentRemoveItems: any = null
578
579 const curPath: string[] = [BASE_PATH].concat(alias.location)
580 for (const prop of propPath) {
581 if (!isDefined(currentItems)) {
582 break
583 }
584
585 curPath.push(prop)
586
587 const config = parsedExpands.get(curPath.join("."))
588 if (config?.isAliasMapping && parentRemoveItems === null) {
589 parentRemoveItems = [currentItems, prop]
590 }
591
592 currentItems = getChildren(currentItems, prop)
593 }
594
595 if (Array.isArray(currentItems)) {
596 if (currentItems.length < 2 && !alias.isList) {
597 locationItem[alias.property] = currentItems.shift()
598 } else {
599 locationItem[alias.property] = currentItems
600 }
601 } else {
602 locationItem[alias.property] = alias.isList
603 ? isDefined(currentItems)
604 ? [currentItems]
605 : []
606 : currentItems
607 }
608
609 if (parentRemoveItems !== null) {
610 cleanup.push(parentRemoveItems)
611 }
612 })
613 }
614
615 for (const [remItems, path] of cleanup) {
616 removeChildren(remItems, path)
617 }
618 }
619
620 function getItemsForPath(rootItems: any[], fullPath: string) {
621 let nestedItems = rootItems
622 const expandedPathLevels = fullPath.split(".")
623
624 for (let idx = 1; idx < expandedPathLevels.length - 1; idx++) {
625 nestedItems = getNestedItems(nestedItems, expandedPathLevels[idx])
626 }
627
628 return nestedItems
629 }
630
631 function computeIdsForRelationship(
632 items: any[],
633 relationship: ComputedJoinerRelationship
634 ): {
635 field: string
636 fieldsArray: string[]
637 idsToFetch: Set<any>
638 } {
639 const field = relationship.inverse
640 ? relationship.primaryKey
641 : relationship.foreignKey.split(".").pop()!
642
643 const fieldsArray = relationship.inverse
644 ? relationship.primaryKeyArr
645 : relationship.foreignKeyArr
646
647 const idsToFetch: Set<any> = new Set()
648 for (const item of items) {
649 if (!item) {
650 continue
651 }
652 const values = fieldsArray.map((f) => item?.[f])
653
654 if (fieldsArray.length === 1) {
655 const val = values[0]
656 if (Array.isArray(val)) {
657 for (const v of val) {
658 idsToFetch.add(v)
659 }
660 } else {
661 idsToFetch.add(val)
662 }
663 } else {
664 idsToFetch.add(values)
665 }
666 }
667
668 return { field, fieldsArray, idsToFetch }
669 }
670
671 function createRelatedDataMap(
672 relatedDataArray: any[],
673 joinFields: string[]
674 ): Record<string, any> {
675 return relatedDataArray.reduce((acc, data) => {
676 const joinValues = joinFields.map((field) => data[field])
677 const key = joinValues.length === 1 ? joinValues[0] : joinValues.join(",")
678
679 let isArray = Array.isArray(acc[key])
680 if (isDefined(acc[key]) && !isArray) {
681 acc[key] = [acc[key]]
682 isArray = true
683 }
684
685 if (isArray) {
686 acc[key].push(data)
687 } else {
688 acc[key] = data
689 }
690 return acc
691 }, {})
692 }
693
694 function assignRelatedToItems(params: {
695 items: any[]
696 relationship: ComputedJoinerRelationship
697 relatedDataMap: Record<string, any>
698 field: string
699 fieldsArray: string[]
700 }): void {
701 const { items, relationship, relatedDataMap, field, fieldsArray } = params
702
703 for (const item of items) {
704 if (!item) {
705 continue
706 }
707
708 const itemKey = fieldsArray.map((f) => item[f]).join(",")
709
710 if (item[relationship.alias]) {
711 if (Array.isArray(item[field])) {
712 for (let i = 0; i < item[relationship.alias].length; i++) {
713 const it = item[relationship.alias][i]
714 item[relationship.alias][i] = Object.assign(
715 it,
716 relatedDataMap[it[relationship.primaryKey]]
717 )
718 }
719 continue
720 }
721
722 item[relationship.alias] = Object.assign(
723 item[relationship.alias],
724 relatedDataMap[itemKey]
725 )
726 continue
727 }
728
729 if (Array.isArray(item[field])) {
730 item[relationship.alias] = item[field].map((id) => {
731 if (relationship.isList && !Array.isArray(relatedDataMap[id])) {
732 relatedDataMap[id] = isDefined(relatedDataMap[id])
733 ? [relatedDataMap[id]]
734 : []
735 }
736 return relatedDataMap[id]
737 })
738 } else {
739 if (relationship.isList && !Array.isArray(relatedDataMap[itemKey])) {
740 relatedDataMap[itemKey] = isDefined(relatedDataMap[itemKey])
741 ? [relatedDataMap[itemKey]]
742 : []
743 }
744 item[relationship.alias] = relatedDataMap[itemKey]
745 }
746 }
747 }
748
749 function mergeInitialData(params: {
750 items: any[]
751 initialData: any[]
752 serviceConfig: InternalJoinerServiceConfig
753 expands?: RemoteNestedExpands
754 relationship?: JoinerRelationship
755 catalog: GraphCatalog
756 }): any[] {
757 const { items, initialData, serviceConfig, expands, relationship, catalog } =
758 params
759
760 if (!initialData.length || !relationship) {
761 return items
762 }
763
764 const primaryKeys = relationship?.primaryKey.split(",") || [
765 serviceConfig.primaryKeys[0],
766 ]
767 const expandKeys = Object.keys(expands ?? {})
768
769 const initialDataIndexMap = new Map(
770 initialData.map((dt, index) => [
771 primaryKeys.map((key) => dt[key]).join(","),
772 index,
773 ])
774 )
775 const itemMap = new Map(
776 items.map((item) => [primaryKeys.map((key) => item[key]).join(","), item])
777 )
778
779 const orderedMergedItems = new Array(initialData.length)
780 for (const [key, index] of initialDataIndexMap.entries()) {
781 const iniData = initialData[index]
782 const item = itemMap.get(key)
783
784 if (!item) {
785 orderedMergedItems[index] = iniData
786 continue
787 }
788
789 const shallowProperty = { ...iniData }
790 for (const expandKey of expandKeys) {
791 const isRel = !!catalog.getEntityRelationship({
792 parentServiceConfig: serviceConfig,
793 property: expandKey,
794 })
795 if (isRel) {
796 Object.defineProperty(shallowProperty, expandKey, {
797 value: undefined,
798 enumerable: false,
799 })
800 }
801 }
802
803 Object.assign(item, shallowProperty)
804 orderedMergedItems[index] = item
805 }
806
807 if (expands) {
808 for (const expand of expandKeys) {
809 mergeInitialData({
810 items: items.flatMap((dt) => dt[expand] ?? []),
811 initialData: initialData
812 .flatMap((dt) => dt[expand] ?? [])
813 .filter(isDefined),
814 serviceConfig,
815 expands: expands[expand]?.expands,
816 relationship: catalog.getEntityRelationship({
817 parentServiceConfig: serviceConfig,
818 property: expand,
819 }),
820 catalog,
821 })
822 }
823 }
824
825 return orderedMergedItems
826 }