Reputation: 1
I'm trying to follow best practices by keeping my entity properties private and accessing them via getters and setters, but I run into a compile-time issue when referencing private properties in TypeORM relationship decorators.
For example, I have the following entity:
import {
Column,
CreateDateColumn,
Entity,
ManyToOne,
PrimaryGeneratedColumn,
} from "typeorm";
import { UserEntity } from "../../auth/models/user.entity";
@Entity("product")
export class ProductEntity {
@PrimaryGeneratedColumn()
private id: number;
@Column({ default: "" })
private body: string;
@CreateDateColumn()
private createdAt: Date;
@ManyToOne(() => UserEntity, user => user.products)
private _creator: UserEntity;
public get creator(): UserEntity {
return this._creator;
}
public set creator(value: UserEntity) {
this._creator = value;
}
}
And the corresponding inverse side in UserEntity:
import { Entity, OneToMany } from "typeorm";
import { ProductEntity } from "./product.entity";
@Entity("user")
export class UserEntity {
@OneToMany(() => ProductEntity, product => product.creator)
private _products: ProductEntity[];
public get products(): ProductEntity[] {
return this._products;
}
}
However, TypeScript complains because the lambda in the relationship decorator on UserEntity (or ProductEntity) is trying to access a private property. I understand that TypeORM uses runtime reflection, so the private modifier doesn't affect the ORM functionality, but it does cause issues at compile time.
One workaround mentioned is to use bracket notation like userEntity["_products"] to bypass TypeScript's access restrictions. Is this an acceptable practice, or is there a better alternative to maintain encapsulation without causing compile-time errors?
Any insights or recommendations would be appreciated. Thanks in advance!
Upvotes: 0
Views: 10