How I can use getter and setter in TypeORM

1个答案

1
最佳答案

In TypeORM, getters and setters can be used to encapsulate entity properties, ensuring the privacy of attributes while allowing specific logic to be executed during read or write operations. Below, I will demonstrate how to use getters and setters in TypeORM with a simple example.

Suppose we have an entity named User with a private password property. We want to ensure that whenever a new password is set, it is automatically encrypted, while keeping the original password inaccessible.

typescript
import { Entity, PrimaryGeneratedColumn, Column, BeforeInsert } from "typeorm"; import * as bcrypt from 'bcryptjs'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column({ type: 'varchar', length: 255 }) private _password: string; // Other properties and columns... constructor(password: string) { this.password = password; } // Use setter to ensure the password is encrypted when set set password(password: string) { const salt = bcrypt.genSaltSync(); this._password = bcrypt.hashSync(password, salt); } // Use getter to retrieve the encrypted password get password(): string { return this._password; } // Define a method to verify the password checkPassword(unencryptedPassword: string): boolean { return bcrypt.compareSync(unencryptedPassword, this._password); } // Ensure the password is encrypted before insertion @BeforeInsert() encryptPassword() { const salt = bcrypt.genSaltSync(); this._password = bcrypt.hashSync(this._password, salt); } }

In the above example, the User entity has a private _password property corresponding to a database column. We define a set password() method to set this private property, which automatically converts plaintext passwords to encrypted form when the user sets the password. We also define a get password() method to read the encrypted password.

We also define a checkPassword() method that accepts an unencrypted password as a parameter and compares it with the encrypted password stored in the database to verify its correctness.

Finally, we use the @BeforeInsert() decorator to mark the encryptPassword() method, ensuring the password is automatically encrypted before inserting the user entity into the database. This is an example of a TypeORM lifecycle hook that automatically executes before certain operations (e.g., insert).

Note that getters and setters themselves do not directly affect database operations; they are part of the entity class for handling read and write operations on instance properties. Database insert and update operations are handled by other components of TypeORM.

2024年6月29日 12:07 回复

你的答案