1 import {
2 DMLSchema,
3 IDmlEntityConfig,
4 RelationshipOptions,
5 } from "@medusajs/types"
6 import { DmlEntity, DMLEntitySchemaBuilder } from "./entity"
7 import { createBigNumberProperties } from "./helpers/entity-builder/create-big-number-properties"
8 import { createDefaultProperties } from "./helpers/entity-builder/create-default-properties"
9 import { FloatProperty } from "./properties"
10 import { ArrayProperty } from "./properties/array"
11 import { AutoIncrementProperty } from "./properties/autoincrement"
12 import { BigNumberProperty } from "./properties/big-number"
13 import { BooleanProperty } from "./properties/boolean"
14 import { DateTimeProperty } from "./properties/date-time"
15 import { EnumLike, EnumProperty } from "./properties/enum"
16 import { IdProperty } from "./properties/id"
17 import { JSONProperty } from "./properties/json"
18 import { NumberProperty } from "./properties/number"
19 import { TextProperty } from "./properties/text"
20 import { BelongsTo } from "./relations/belongs-to"
21 import { HasMany } from "./relations/has-many"
22 import { HasOne } from "./relations/has-one"
23 import { HasOneWithForeignKey } from "./relations/has-one-fk"
24 import { ManyToMany } from "./relations/many-to-many"
25
26 /**
27 * The implicit properties added by EntityBuilder in every schema
28 */
29 const IMPLICIT_PROPERTIES = ["created_at", "updated_at", "deleted_at"]
30
31 export type DefineOptions =
32 | string
33 | {
34 /**
35 * The data model's name.
36 */
37 name?: string
38 /**
39 * The name of the data model's table in the database.
40 */
41 tableName: string
42 }
43
44 export type ManyToManyOptions = RelationshipOptions &
45 (
46 | {
47 /**
48 * The name of the pivot table
49 * created in the database for this relationship.
50 */
51 pivotTable?: string
52 /**
53 * @ignore
54 */
55 pivotEntity?: never
56 /**
57 * The column name in the pivot table that for the current entity
58 */
59 joinColumn?: string | string[]
60 /**
61 * The column name in the pivot table for the opposite entity
62 */
63 inverseJoinColumn?: string | string[]
64 }
65 | {
66 /**
67 * @ignore
68 */
69 pivotTable?: never
70 /**
71 * A function that returns the data model
72 * representing the pivot table created in the
73 * database for this relationship.
74 */
75 pivotEntity?: () => DmlEntity<any, any>
76 /**
77 * The column name in the pivot table that for the current entity
78 */
79 joinColumn?: string | string[]
80 /**
81 * The column name in the pivot table for the opposite entity
82 */
83 inverseJoinColumn?: string | string[]
84 }
85 )
86
87 /**
88 * Entity builder exposes the API to create an entity and define its
89 * schema using the shorthand methods.
90 */
91 export class EntityBuilder {
92 #disallowImplicitProperties(schema: DMLSchema) {
93 const implicitProperties = Object.keys(schema).filter((fieldName) =>
94 IMPLICIT_PROPERTIES.includes(fieldName)
95 )
96
97 if (implicitProperties.length) {
98 throw new Error(
99 `Cannot define field(s) "${implicitProperties.join(
100 ","
101 )}" as they are implicitly defined on every model`
102 )
103 }
104 }
105
106 /**
107 * This method defines a data model.
108 *
109 * @typeParam Schema - The type of the accepted schema in the second parameter of the method.
110 *
111 * @param {DefineOptions} nameOrConfig - Either the data model's name, or configurations to name the data model.
112 * The data model's name must be unique.
113 * @param {Schema} schema - The schema of the data model's properties.
114 *
115 * @example
116 * import { model } from "@medusajs/framework/utils"
117 *
118 * const MyCustom = model.define("my_custom", {
119 * id: model.id(),
120 * name: model.text(),
121 * })
122 *
123 * export default MyCustom
124 */
125 define<Schema extends DMLSchema, const TConfig extends IDmlEntityConfig>(
126 nameOrConfig: TConfig,
127 schema: Schema
128 ): DmlEntity<DMLEntitySchemaBuilder<Schema>, TConfig> {
129 this.#disallowImplicitProperties(schema)
130
131 return new DmlEntity(nameOrConfig, {
132 ...schema,
133 ...createBigNumberProperties(schema),
134 ...createDefaultProperties(),
135 }) as unknown as DmlEntity<DMLEntitySchemaBuilder<Schema>, TConfig>
136 }
137
138 /**
139 * This method defines an automatically generated string ID property.
140 *
141 * You must use the "primaryKey" modifier to mark the property as the
142 * primary key.
143 *
144 * @example
145 * import { model } from "@medusajs/framework/utils"
146 *
147 * const User = model.define("User", {
148 * id: model.id().primaryKey(),
149 * // ...
150 * })
151 *
152 * export default User
153 *
154 * @customNamespace Property Types
155 */
156 id(options?: { prefix?: string }) {
157 return new IdProperty(options)
158 }
159
160 /**
161 * This method defines a string property.
162 *
163 * @example
164 * import { model } from "@medusajs/framework/utils"
165 *
166 * const MyCustom = model.define("my_custom", {
167 * name: model.text(),
168 * // ...
169 * })
170 *
171 * export default MyCustom
172 *
173 * @customNamespace Property Types
174 */
175 text() {
176 return new TextProperty()
177 }
178
179 /**
180 * This method defines a boolean property.
181 *
182 * @example
183 * import { model } from "@medusajs/framework/utils"
184 *
185 * const MyCustom = model.define("my_custom", {
186 * hasAccount: model.boolean(),
187 * // ...
188 * })
189 *
190 * export default MyCustom
191 *
192 * @customNamespace Property Types
193 */
194 boolean() {
195 return new BooleanProperty()
196 }
197
198 /**
199 * This method defines a number property.
200 *
201 * @example
202 * import { model } from "@medusajs/framework/utils"
203 *
204 * const MyCustom = model.define("my_custom", {
205 * age: model.number(),
206 * // ...
207 * })
208 *
209 * export default MyCustom
210 *
211 * @customNamespace Property Types
212 */
213 number() {
214 return new NumberProperty()
215 }
216
217 /**
218 * This method defines a number property that expects large numbers, such as prices.
219 *
220 * @example
221 * import { model } from "@medusajs/framework/utils"
222 *
223 * const MyCustom = model.define("my_custom", {
224 * price: model.bigNumber(),
225 * // ...
226 * })
227 *
228 * export default MyCustom
229 *
230 * @customNamespace Property Types
231 *
232 * @privateRemarks
233 * This property produces an additional
234 * column - raw_{{ property_name }}, which stores the configuration
235 * of bignumber (https://github.com/MikeMcl/bignumber.js)
236 */
237 bigNumber() {
238 return new BigNumberProperty()
239 }
240
241 /**
242 * This method defines a float property that allows for
243 * values with decimal places
244 *
245 * @since 2.1.2
246 *
247 * @example
248 * import { model } from "@medusajs/framework/utils"
249 *
250 * const MyCustom = model.define("tax", {
251 * tax_rate: model.float(),
252 * // ...
253 * })
254 *
255 * export default MyCustom
256 *
257 * @customNamespace Property Types
258 */
259 float() {
260 return new FloatProperty()
261 }
262
263 /**
264 * This method defines an autoincrement property.
265 *
266 * @example
267 * import { model } from "@medusajs/framework/utils"
268 *
269 * const MyCustom = model.define("my_custom", {
270 * serial_id: model.autoincrement(),
271 * // ...
272 * })
273 *
274 * export default MyCustom
275 *
276 * @customNamespace Property
277 */
278
279 autoincrement() {
280 return new AutoIncrementProperty()
281 }
282
283 /**
284 * This method defines an array of strings property.
285 *
286 * @example
287 * import { model } from "@medusajs/framework/utils"
288 *
289 * const MyCustom = model.define("my_custom", {
290 * names: model.array(),
291 * // ...
292 * })
293 *
294 * export default MyCustom
295 *
296 * @customNamespace Property Types
297 */
298 array() {
299 return new ArrayProperty()
300 }
301
302 /**
303 * This method defines a timestamp property.
304 *
305 * @example
306 * import { model } from "@medusajs/framework/utils"
307 *
308 * const MyCustom = model.define("my_custom", {
309 * date_of_birth: model.dateTime(),
310 * // ...
311 * })
312 *
313 * export default MyCustom
314 *
315 * @customNamespace Property Types
316 */
317 dateTime() {
318 return new DateTimeProperty()
319 }
320
321 /**
322 * This method defines a property whose value is stringified JSON. The
323 * value is stored in a `jsonb` column, so any JSON-serializable value
324 * is supported, including arrays.
325 *
326 * @typeParam T - The type of the stored JSON value. By default, it's
327 * a JSON object (`Record<string, unknown>`). Pass a type parameter to
328 * store another shape, such as an array of objects. To store an array
329 * of strings, consider using {@link array} instead, which stores the
330 * value in a `text[]` column.
331 *
332 * @example
333 * import { model } from "@medusajs/framework/utils"
334 *
335 * const MyCustom = model.define("my_custom", {
336 * metadata: model.json(),
337 * warnings: model.json<{ code: string; message: string }[]>(),
338 * // ...
339 * })
340 *
341 * export default MyCustom
342 *
343 * @customNamespace Property Types
344 */
345 json<T = Record<string, unknown>>(): JSONProperty<NoInfer<T>> {
346 return new JSONProperty<T>()
347 }
348
349 /**
350 * This method defines a property whose value can only be one of the specified values.
351 *
352 * @typeParam Values - The type of possible values. By default, it's `string`.
353 *
354 * @param {Values[]} values - An array of possible values.
355 *
356 * @example
357 * import { model } from "@medusajs/framework/utils"
358 *
359 * const MyCustom = model.define("my_custom", {
360 * color: model.enum(["black", "white"]),
361 * // ...
362 * })
363 *
364 * export default MyCustom
365 *
366 * @customNamespace Property Types
367 */
368 enum<const Values extends unknown[] | EnumLike>(values: Values) {
369 return new EnumProperty<Values>(values)
370 }
371
372 /**
373 * This method defines a relationship between two data models,
374 * where the owner of the relationship has one record of the related
375 * data model.
376 *
377 * For example: A user "hasOne" email.
378 *
379 * Use the {@link belongsTo} method to define the inverse of this relationship in
380 * the other data model.
381 *
382 * @typeParam T - The type of the entity builder passed as a first parameter. By default, it's
383 * a function returning the related model.
384 *
385 * @param {T} entityBuilder - A function that returns the data model this model is related to.
386 * @param {RelationshipOptions} options - The relationship's options.
387 *
388 * @example
389 * import { model } from "@medusajs/framework/utils"
390 *
391 * const User = model.define("user", {
392 * id: model.id(),
393 * email: model.hasOne(() => Email),
394 * })
395 *
396 * @customNamespace Relationship Methods
397 */
398 hasOne<T, const ForeignKeyName extends string | undefined = undefined>(
399 entityBuilder: T,
400 options: RelationshipOptions & {
401 foreignKey: true
402 foreignKeyName?: ForeignKeyName
403 }
404 ): HasOneWithForeignKey<T, ForeignKeyName>
405 hasOne<T>(
406 entityBuilder: T,
407 options?: RelationshipOptions & {
408 foreignKey?: false
409 }
410 ): HasOne<T>
411 hasOne<T, const ForeignKeyName extends string | undefined = undefined>(
412 entityBuilder: T,
413 options?: RelationshipOptions & {
414 foreignKey?: boolean
415 foreignKeyName?: ForeignKeyName
416 }
417 ): HasOneWithForeignKey<T, ForeignKeyName> | HasOne<T> {
418 if (options?.foreignKey) {
419 return new HasOneWithForeignKey<T, ForeignKeyName>(
420 entityBuilder,
421 options || {}
422 )
423 }
424 return new HasOne<T>(entityBuilder, options || {})
425 }
426
427 /**
428 * This method defines the inverse of the {@link hasOne} or {@link hasMany} relationship.
429 *
430 * For example, a product "belongsTo" a store.
431 *
432 * @typeParam T - The type of the entity builder passed as a first parameter. By default, it's
433 * a function returning the related model.
434 *
435 * @param {T} entityBuilder - A function that returns the data model this model is related to.
436 * @param {RelationshipOptions} options - The relationship's options.
437 *
438 * @example
439 * import { model } from "@medusajs/framework/utils"
440 *
441 * const Product = model.define("product", {
442 * id: model.id(),
443 * store: model.belongsTo(() => Store, {
444 * mappedBy: "products",
445 * }),
446 * })
447 *
448 * @customNamespace Relationship Methods
449 */
450 belongsTo<T, const ForeignKeyName extends string | undefined = undefined>(
451 entityBuilder: T,
452 options?: RelationshipOptions & {
453 foreignKeyName?: ForeignKeyName
454 }
455 ) {
456 return new BelongsTo<T, ForeignKeyName>(entityBuilder, options || {})
457 }
458
459 /**
460 * This method defines a relationship between two data models,
461 * where the owner of the relationship has many records of the related
462 * data model, but the related data model only has one owner.
463 *
464 * For example, a store "hasMany" products.
465 *
466 * @typeParam T - The type of the entity builder passed as a first parameter. By default, it's
467 * a function returning the related model.
468 *
469 * @param {T} entityBuilder - A function that returns the data model this model is related to.
470 * @param {RelationshipOptions} options - The relationship's options.
471 *
472 * @example
473 * import { model } from "@medusajs/framework/utils"
474 *
475 * const Store = model.define("store", {
476 * id: model.id(),
477 * products: model.hasMany(() => Product),
478 * })
479 *
480 * @customNamespace Relationship Methods
481 */
482 hasMany<T>(entityBuilder: T, options?: RelationshipOptions) {
483 return new HasMany<T>(entityBuilder, options || {})
484 }
485
486 /**
487 * This method defines a relationship between two data models,
488 * where both data models have many related records.
489 *
490 * For example, an order is associated with many products, and a product
491 * is associated with many orders.
492 *
493 * @typeParam T - The type of the entity builder passed as a first parameter. By default, it's
494 * a function returning the related model.
495 *
496 * @param {T} entityBuilder - A function that returns the data model this model is related to.
497 * @param {RelationshipOptions} options - The relationship's options.
498 *
499 * @example
500 * import { model } from "@medusajs/framework/utils"
501 *
502 * const Order = model.define("order", {
503 * id: model.id(),
504 * products: model.manyToMany(() => Product),
505 * })
506 *
507 * const Product = model.define("product", {
508 * id: model.id(),
509 * order: model.manyToMany(() => Order),
510 * })
511 *
512 * @customNamespace Relationship Methods
513 */
514 manyToMany<T>(entityBuilder: T, options?: ManyToManyOptions) {
515 return new ManyToMany<T>(entityBuilder, options || {})
516 }
517 }
518
519 export const model = new EntityBuilder()