乐闻世界logo
搜索文章和话题

How to add a helper method to a typeORM entity?

1个答案

1

When using TypeORM, it is typically not recommended to directly add helper methods to the entity class. This is because entities should remain concise, containing only data definitions and relationship mappings. However, if you do need to add helper methods to the entity, you can define them as member methods of the entity class.

Here is a simple example. Suppose we have a User entity, and we want to add a helper method to check if a user's password matches the stored hashed password:

typescript
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from 'typeorm'; import * as bcrypt from 'bcrypt'; @Entity() export class User extends BaseEntity { @PrimaryGeneratedColumn() id: number; @Column() username: string; @Column() password: string; // Helper method, used to check if password matches async validatePassword(inputPassword: string): Promise<boolean> { return bcrypt.compare(inputPassword, this.password); } }

In this example, we define a validatePassword method within the User entity that accepts an input password and uses the bcrypt library to compare the input password with the stored hashed password. This method returns a Promise because bcrypt.compare is an asynchronous operation.

To use this helper method, you can call it in your business logic as shown below:

typescript
async function login(username: string, inputPassword: string): Promise<User | null> { // Find user by username const user = await User.findOne({ where: { username: username } }); if (user) { // Use the helper method on the entity to check password const isPasswordValid = await user.validatePassword(inputPassword); if (isPasswordValid) { return user; // Login successful } } return null; // Login failed }

However, it is important to note that while adding helper methods to the entity class is possible, the recommended practice is typically to place this business logic in the service layer. The reason is that entities should focus on representing the data structure in the database rather than encapsulating business logic. Business logic can be placed in the service layer, which makes the code more modular, easier to unit test, and maintain.

2024年6月29日 12:07 回复

你的答案