1 import {
2 CheckConstraint,
3 DMLSchema,
4 EntityCascades,
5 EntityIndex,
6 ExtractEntityRelations,
7 IDmlEntity,
8 IDmlEntityConfig,
9 InferDmlEntityNameFromConfig,
10 PropertyType,
11 QueryCondition,
12 } from "@medusajs/types"
13 import { isObject, isString, toCamelCase, upperCaseFirst } from "../common"
14 import { transformIndexWhere } from "./helpers/entity-builder/build-indexes"
15 import { DMLSchemaWithBigNumber } from "./helpers/entity-builder/create-big-number-properties"
16 import { DMLSchemaDefaults } from "./helpers/entity-builder/create-default-properties"
17 import { BelongsTo } from "./relations/belongs-to"
18
19 const IsDmlEntity = Symbol.for("isDmlEntity")
20
21 /**
22 * Represents an entity with translatable properties
23 */
24 export type TranslatableEntityEntry = {
25 /**
26 * The entity name (PascalCase)
27 */
28 entity: string
29 /**
30 * The list of translatable property names
31 */
32 fields: string[]
33 }
34
35 /**
36 * Module-level storage for translatable entities using Map for O(1) lookups.
37 * Keys are entity names (PascalCase), values are Sets of field names.
38 *
39 * @example
40 * import { DmlEntity } from "@medusajs/framework/utils"
41 *
42 * const translatables = DmlEntity.getTranslatableEntities()
43 * // Returns: [{ entity: "Store", fields: ["name"] }]
44 */
45 const TRANSLATABLE_ENTITIES = new Map<string, Set<string>>()
46
47 export type DMLEntitySchemaBuilder<Schema extends DMLSchema> =
48 DMLSchemaWithBigNumber<Schema> & DMLSchemaDefaults & Schema
49
50 function extractNameAndTableName<const Config extends IDmlEntityConfig>(
51 nameOrConfig: Config
52 ) {
53 const result = {
54 name: "",
55 tableName: "",
56 } as {
57 name: InferDmlEntityNameFromConfig<Config>
58 tableName: string
59 }
60
61 if (isString(nameOrConfig)) {
62 const [schema, ...rest] = nameOrConfig.split(".")
63 const name = rest.length ? rest.join(".") : schema
64 result.name = upperCaseFirst(
65 toCamelCase(name)
66 ) as InferDmlEntityNameFromConfig<Config>
67
68 result.tableName = nameOrConfig
69 }
70
71 if (isObject(nameOrConfig)) {
72 if (!nameOrConfig.tableName) {
73 throw new Error(
74 `Missing "tableName" property in the config object for "${nameOrConfig.name}" entity`
75 )
76 }
77
78 const potentialName = nameOrConfig.name ?? nameOrConfig.tableName
79 const [schema, ...rest] = potentialName.split(".")
80 const name = rest.length ? rest.join(".") : schema
81
82 result.name = upperCaseFirst(
83 toCamelCase(name)
84 ) as InferDmlEntityNameFromConfig<Config>
85 result.tableName = nameOrConfig.tableName
86 }
87
88 return result
89 }
90
91 /**
92 * Dml entity is a representation of a DML model with a unique
93 * name, its schema and relationships.
94 */
95 export class DmlEntity<
96 const Schema extends DMLSchema,
97 const TConfig extends IDmlEntityConfig
98 > implements IDmlEntity<Schema, TConfig>
99 {
100 [IsDmlEntity] = true
101
102 name: InferDmlEntityNameFromConfig<TConfig>
103 schema: Schema
104
105 readonly #tableName: string
106 #cascades: EntityCascades<string[], string[]> = {}
107
108 #indexes: EntityIndex<Schema>[] = []
109 #checks: CheckConstraint<Schema>[] = []
110
111 constructor(nameOrConfig: TConfig, schema: Schema) {
112 const { name, tableName } = extractNameAndTableName(nameOrConfig)
113 this.schema = schema
114 this.name = name
115 this.#tableName = tableName
116
117 this.#registerTranslatableFields(name, schema)
118 }
119
120 /**
121 * Collects translatable fields from the schema and registers them
122 */
123 #registerTranslatableFields(entityName: string, schema: Schema): void {
124 for (const [fieldName, property] of Object.entries(schema)) {
125 if (typeof (property as PropertyType<any>).parse !== "function") {
126 continue
127 }
128
129 const parsed = (property as PropertyType<any>).parse(fieldName)
130 if (!("fieldName" in parsed) || !parsed.dataType?.options?.translatable) {
131 continue
132 }
133
134 // Get or create the Set for this entity
135 const existingFields = TRANSLATABLE_ENTITIES.get(entityName)
136 if (existingFields) {
137 existingFields.add(fieldName)
138 } else {
139 TRANSLATABLE_ENTITIES.set(entityName, new Set([fieldName]))
140 }
141 }
142 }
143
144 /**
145 * A static method to check if an entity is an instance of DmlEntity.
146 * It allows us to identify a specific object as being an instance of
147 * DmlEntity.
148 *
149 * @param entity
150 */
151 static isDmlEntity(entity: unknown): entity is DmlEntity<any, any> {
152 return !!entity?.[IsDmlEntity]
153 }
154
155 /**
156 * Returns all registered translatable entities with their translatable fields.
157 * Each entry contains the entity name (PascalCase) and an array
158 * of field names that are marked as translatable.
159 *
160 * @example
161 * import { DmlEntity } from "@medusajs/framework/utils"
162 *
163 * const translatables = DmlEntity.getTranslatableEntities()
164 * // Returns: [{ entity: "Store", fields: ["name"] }]
165 *
166 * @customNamespace Model Methods
167 */
168 static getTranslatableEntities(): TranslatableEntityEntry[] {
169 return Array.from(TRANSLATABLE_ENTITIES.entries()).map(
170 ([entity, fields]) => ({
171 entity,
172 fields: Array.from(fields),
173 })
174 )
175 }
176
177 /**
178 * Clears all registered translatable entities.
179 * This is primarily used for testing purposes.
180 */
181 static clearTranslatableEntities(): void {
182 TRANSLATABLE_ENTITIES.clear()
183 }
184
185 /**
186 * Parse entity to get its underlying information
187 */
188 parse(): {
189 name: InferDmlEntityNameFromConfig<TConfig>
190 tableName: string
191 schema: DMLSchema
192 cascades: EntityCascades<string[], string[]>
193 indexes: EntityIndex<Schema>[]
194 checks: CheckConstraint<Schema>[]
195 } {
196 return {
197 name: this.name,
198 tableName: this.#tableName,
199 schema: this.schema,
200 cascades: this.#cascades,
201 indexes: this.#indexes,
202 checks: this.#checks,
203 }
204 }
205
206 /**
207 * This method configures which related data models an operation, such as deletion,
208 * should be cascaded to.
209 *
210 * For example, if a store is deleted, its product should also be deleted.
211 *
212 * @param options - The cascades configurations. They object's keys are the names of
213 * the actions, such as `deleted`, and the value is an array of relations that the
214 * action should be cascaded to.
215 *
216 * @example
217 * import { model } from "@medusajs/framework/utils"
218 *
219 * const Store = model.define("store", {
220 * id: model.id(),
221 * products: model.hasMany(() => Product),
222 * })
223 * .cascades({
224 * delete: ["products"],
225 * })
226 *
227 * @customNamespace Model Methods
228 */
229 cascades(
230 options: EntityCascades<
231 ExtractEntityRelations<Schema, "hasOne" | "hasOneWithFK" | "hasMany">,
232 ExtractEntityRelations<Schema, "manyToMany">
233 >
234 ) {
235 const childToParentCascades = options.delete?.filter((relationship) => {
236 return BelongsTo.isBelongsTo(this.schema[relationship])
237 })
238
239 if (childToParentCascades?.length) {
240 throw new Error(
241 `Cannot cascade delete "${childToParentCascades.join(
242 ", "
243 )}" relationship(s) from "${
244 this.name
245 }" entity. Child to parent cascades are not allowed`
246 )
247 }
248
249 this.#cascades = options
250 return this
251 }
252
253 /**
254 * This method defines indices on the data model. An index can be on multiple columns
255 * and have conditions.
256 *
257 * @param indexes - The index's configuration.
258 *
259 * @example
260 * An example of a simple index:
261 *
262 * ```ts
263 * import { model } from "@medusajs/framework/utils"
264 *
265 * const MyCustom = model.define("my_custom", {
266 * id: model.id(),
267 * name: model.text(),
268 * age: model.number()
269 * }).indexes([
270 * {
271 * on: ["name", "age"],
272 * },
273 * ])
274 *
275 * export default MyCustom
276 * ```
277 *
278 * To add a condition on the index, use the `where` option:
279 *
280 * ```ts
281 * import { model } from "@medusajs/framework/utils"
282 *
283 * const MyCustom = model.define("my_custom", {
284 * id: model.id(),
285 * name: model.text(),
286 * age: model.number()
287 * }).indexes([
288 * {
289 * on: ["name", "age"],
290 * where: {
291 * age: 30
292 * }
293 * },
294 * ])
295 *
296 * export default MyCustom
297 * ```
298 *
299 * The condition can also be a negation. For example:
300 *
301 * ```ts
302 * import { model } from "@medusajs/framework/utils"
303 *
304 * const MyCustom = model.define("my_custom", {
305 * id: model.id(),
306 * name: model.text(),
307 * age: model.number()
308 * }).indexes([
309 * {
310 * on: ["name", "age"],
311 * where: {
312 * age: {
313 * $ne: 30
314 * }
315 * }
316 * },
317 * ])
318 *
319 * export default MyCustom
320 * ```
321 *
322 * In this example, the index is created when the value of `age` doesn't equal `30`.
323 *
324 * @customNamespace Model Methods
325 */
326 indexes(indexes: EntityIndex<Schema, string | QueryCondition<Schema>>[]) {
327 for (const index of indexes) {
328 index.where = transformIndexWhere<Schema>(index)
329 index.unique ??= false
330 }
331
332 this.#indexes = indexes as EntityIndex<Schema>[]
333 return this
334 }
335
336 checks(checks: CheckConstraint<Schema>[]) {
337 this.#checks = checks
338 return this
339 }
340 }