1 import { MedusaContainer, RemoteQueryFunction } from "@medusajs/types"
2 import { ContainerRegistrationKeys } from "../common/container"
3 import { isObject } from "../common/is-object"
4 import { FeatureFlag } from "../feature-flags/flag-router"
5
6 const excludedKeys = [
7 "id",
8 "created_at",
9 "updated_at",
10 "deleted_at",
11 "metadata",
12 ]
13
14 function canApplyTranslationTo(object: Record<string, any>) {
15 return isObject(object) && "id" in object && !!object.id
16 }
17
18 function gatherIds(object: Record<string, any>, gatheredIds: Set<string>) {
19 if (!isObject(object)) {
20 return
21 }
22
23 if (object.id) {
24 gatheredIds.add(object.id)
25 }
26
27 Object.entries(object).forEach(([, value]) => {
28 if (Array.isArray(value)) {
29 value.forEach((item) => item && gatherIds(item, gatheredIds))
30 } else if (isObject(value)) {
31 gatherIds(value, gatheredIds)
32 }
33 })
34 }
35
36 function isEmptyStringTranslation(value: unknown): boolean {
37 return typeof value === "string" && value.trim() === ""
38 }
39
40 function applyTranslation(
41 object: Record<string, any>,
42 entityIdToTranslation: Map<string, Record<string, any>>
43 ) {
44 const translation = entityIdToTranslation.get(object.id)
45 const hasTranslation = !!translation
46
47 Object.entries(object).forEach(([key, value]) => {
48 if (excludedKeys.includes(key)) {
49 return
50 }
51
52 if (hasTranslation) {
53 if (
54 key in translation &&
55 typeof object[key] === typeof translation[key] &&
56 !isEmptyStringTranslation(translation[key])
57 ) {
58 object[key] = translation[key]
59 return
60 }
61 }
62
63 if (Array.isArray(value)) {
64 value.forEach(
65 (item) =>
66 item &&
67 canApplyTranslationTo(item) &&
68 applyTranslation(item, entityIdToTranslation)
69 )
70 } else if (isObject(value) && canApplyTranslationTo(value)) {
71 applyTranslation(value, entityIdToTranslation)
72 }
73 })
74 }
75
76 export async function applyTranslations({
77 localeCode,
78 objects,
79 container,
80 }: {
81 localeCode: string | undefined
82 objects: Record<string, any>[]
83 container: MedusaContainer
84 }) {
85 const isTranslationEnabled = FeatureFlag.isFeatureEnabled("translation")
86
87 if (!isTranslationEnabled) {
88 return
89 }
90
91 const locale = localeCode
92
93 if (!locale) {
94 return
95 }
96
97 const objects_ = objects.filter((o) => !!o)
98 if (!objects_.length) {
99 return
100 }
101
102 const gatheredIds: Set<string> = new Set()
103
104 for (const inputObject of objects_) {
105 gatherIds(inputObject, gatheredIds)
106 }
107
108 const query = container.resolve<RemoteQueryFunction>(
109 ContainerRegistrationKeys.QUERY
110 )
111
112 const queryBatchSize = 250
113 const queryBatches = Math.ceil(gatheredIds.size / queryBatchSize)
114
115 const entityIdToTranslation = new Map<string, Record<string, any>>()
116
117 for (let i = 0; i < queryBatches; i++) {
118 // TODO: concurrently fetch if needed
119 const queryBatch = Array.from(gatheredIds)
120 .slice(i * queryBatchSize, (i + 1) * queryBatchSize)
121 .sort()
122
123 const { data: translations } = await query.graph(
124 {
125 entity: "translations",
126 fields: ["translations", "reference_id"],
127 filters: {
128 reference_id: queryBatch,
129 locale_code: locale,
130 },
131 pagination: {
132 take: queryBatchSize,
133 },
134 },
135 {
136 cache: { enable: true },
137 }
138 )
139
140 for (const translation of translations) {
141 entityIdToTranslation.set(
142 translation.reference_id,
143 translation.translations ?? {}
144 )
145 }
146 }
147
148 for (const inputObject of objects_) {
149 applyTranslation(inputObject, entityIdToTranslation)
150 }
151 }