Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can use getter and setter in TypeORm

How I can use getter and setter in TypeOrm.

I saw issues in here and also here, but not found answer

For example a left my User entity

export class User {
    @PrimaryGeneratedColumn()
    private id: number;

    @Column()
    @Length(4, 20)
    @IsNotEmpty()
    private name: string;

    @Column()
    @Length(4, 100)
    @IsNotEmpty()
    private password: string;

    public getId(): number {
        return this.id;
    }

    public getPassword(password: string): string {
        return this.password;
    }

    public setPassword(password: string): User {
        this.password = bcrypt.hashSync(password, 8);

        return this;
    }

    public setName(name: string): User {
        this.name = name;

        return this;
    }
}

I use orm version 0.2.7

like image 930
pavel Avatar asked Feb 23 '20 16:02

pavel


1 Answers

@BeforeInsert & @AfterLoad

BeforeInsert https://typeorm.io/#/listeners-and-subscribers/beforeinsert
AfterLoad https://typeorm.io/#/listeners-and-subscribers/afterload

Use @BeforeInsert as setter
Use @AfterLoad as getter

like image 148
Zawad Avatar answered Sep 16 '22 13:09

Zawad