1 import {
2 RelationshipMetadata,
3 RelationshipOptions,
4 RelationshipType,
5 RelationshipTypes,
6 } from "@medusajs/types"
7
8 export const IsRelationship = Symbol.for("isRelationship")
9
10 /**
11 * The BaseRelationship encapsulates the repetitive parts of defining
12 * a relationship
13 */
14 export abstract class BaseRelationship<T> implements RelationshipType<T> {
15 [IsRelationship]: true = true
16
17 #searchable: boolean = false
18 #referencedEntity: T
19
20 /**
21 * Configuration options for the relationship
22 */
23 protected options: RelationshipOptions
24
25 /**
26 * Relationship type
27 */
28 abstract type: RelationshipTypes
29
30 /**
31 * A type-only property to infer the JavScript data-type
32 * of the relationship property
33 */
34 declare $dataType: T
35
36 static isRelationship<T>(
37 relationship: any
38 ): relationship is BaseRelationship<T> {
39 return !!relationship?.[IsRelationship]
40 }
41
42 constructor(referencedEntity: T, options: RelationshipOptions) {
43 this.#referencedEntity = referencedEntity
44 this.options = options
45 }
46
47 /**
48 * This method indicates that the relationship is searchable
49 *
50 * @example
51 * import { model } from "@medusajs/framework/utils"
52 *
53 * const Product = model.define("Product", {
54 * variants: model.hasMany(() => ProductVariant).searchable(),
55 * // ...
56 * })
57 *
58 * export default Product
59 */
60 searchable() {
61 this.#searchable = true
62 return this
63 }
64
65 /**
66 * Returns the parsed copy of the relationship
67 */
68 parse(relationshipName: string): RelationshipMetadata {
69 return {
70 name: relationshipName,
71 nullable: false,
72 ...("mappedBy" in this.options
73 ? { mappedBy: this.options.mappedBy }
74 : {}),
75 options: this.options,
76 searchable: this.#searchable,
77 entity: this.#referencedEntity,
78 type: this.type,
79 }
80 }
81 }