| 27 | |
| 28 | /** Wrapper around an entity that provides lazy loading capabilities and identity-preserving reference semantics. */ |
| 29 | export class Reference<T extends object> { |
| 30 | private property?: EntityProperty; |
| 31 | |
| 32 | constructor(private entity: T) { |
| 33 | Object.defineProperty(this, referenceSymbol, { value: true, enumerable: false }); |
| 34 | this.set(entity); |
| 35 | const meta = helper(this.entity).__meta; |
| 36 | |
| 37 | meta.primaryKeys.forEach(primaryKey => { |
| 38 | Object.defineProperty(this, primaryKey, { |
| 39 | get() { |
| 40 | return this.entity[primaryKey]; |
| 41 | }, |
| 42 | }); |
| 43 | }); |
| 44 | |
| 45 | if (meta.serializedPrimaryKey && meta.primaryKeys[0] !== meta.serializedPrimaryKey) { |
| 46 | Object.defineProperty(this, meta.serializedPrimaryKey, { |
| 47 | get() { |
| 48 | return helper(this.entity).getSerializedPrimaryKey(); |
| 49 | }, |
| 50 | }); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | /** Creates a Reference wrapper for the given entity, preserving identity if one already exists. */ |
| 55 | static create<T extends object>(entity: T | Ref<T>): Ref<T> { |
| 56 | const unwrapped = Reference.unwrapReference(entity); |
| 57 | const ref = helper(entity).toReference() as Reference<T>; |
| 58 | |
| 59 | if (unwrapped !== ref.unwrap()) { |
| 60 | ref.set(unwrapped); |
| 61 | } |
| 62 | |
| 63 | return ref as Ref<T>; |
| 64 | } |
| 65 | |
| 66 | /** Creates a Reference wrapper for an entity identified by its primary key, wrapped in a Ref. */ |
| 67 | static createFromPK<T extends object>( |
| 68 | entityType: EntityClass<T>, |
| 69 | pk: Primary<T>, |
| 70 | options?: { schema?: string }, |
| 71 | ): Ref<T> { |
| 72 | const ref = this.createNakedFromPK(entityType, pk, options); |
| 73 | return helper(ref)?.toReference() ?? ref; |
| 74 | } |
| 75 | |
| 76 | /** Creates an uninitialized entity reference by primary key without wrapping it in a Reference. */ |
| 77 | static createNakedFromPK<T extends object>( |
| 78 | entityType: EntityClass<T>, |
| 79 | pk: Primary<T>, |
| 80 | options?: { schema?: string }, |
| 81 | ): T { |
| 82 | const factory = entityType.prototype.__factory as EntityFactory; |
| 83 | |
| 84 | if (!factory) { |
| 85 | // this can happen only if `ref()` is used as a property initializer, and the value is important only for the |
| 86 | // inference of defaults, so it's fine to return it directly without wrapping with `Reference` class |
nothing calls this directly
no outgoing calls
no test coverage detected