问题描述
我正在将Nest.Js与TypeORM一起使用,并且我想先将哈希密码存储在数据库中。
I am using Nest.Js with TypeORM and I want to hash my password before persisting into the DB.
我尝试使用事件装饰器 @BeforeInsert (),但是它对我不起作用,但后来我发现它不起作用,因为我将DTO作为输入。
I tried using the event decorator @BeforeInsert() however it wasn't working for me but later I found that it was not working because I was taking an DTO as an input.
user.controller.ts
@Post()
async create(@Body() data: CreateUserDto, @Res() res) {
// if user already exist
const isUserExist = await this.service.findByEmail(data.email);
if (isUserExist) {
throw new BadRequestException('Email already exist');
}
// insert user
this.service.create(data);
// send response
return res.status(201).json({
statusCode: 201,
message: 'User added Successfully',
});
}
user.service.ts
create(data: CreateUserDto) {
return this.userRepository.save(data)
}
因此,我基本上是使用DTO来保存数据。这就是为什么它不起作用。
So, I was basically using an DTO to save the data. That's why it was not working.
但是我要做的是将DTO映射到用户对象。因此,这就是我的工作。
But what I want to do is map the DTO to user object. So, This is what I did.
@Post()
async create(@Body() data: CreateUserDto, @Res() res) {
// Create User object
const user = new User();
// Map DTO to User object
for (const [key, value] of Object.entries(data)) {
user[key] = value;
}
// if user already exist
const isUserExist = await this.service.findByEmail(user.email);
if (isUserExist) {
throw new BadRequestException('Email already exist');
}
// insert user
this.service.create(user);
// send response
return res.status(201).json({
statusCode: 201,
message: 'User added Successfully',
});
}
create-user.dto.ts
import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class CreateUserDto {
@IsNotEmpty()
@IsString()
@ApiProperty()
readonly firstName: string;
@IsNotEmpty()
@IsString()
@ApiProperty()
readonly lastName: string;
@IsNotEmpty()
@IsString()
@IsEmail()
@ApiProperty()
readonly email: string;
@IsNotEmpty()
@IsString()
@ApiProperty()
readonly password: string;
}
有没有更好的方法?因为当前我必须在每种方法中编写代码才能对其进行映射。
Is there any better approach for this? Because currently I have to write the code in every method to map it.
推荐答案
我们可以轻松地映射通过使用
'class-transformer'
包
答案:
async create(@Body() data: CreateUserDto, @Res() res) {
const user = plainToClass(User, data)
}
这篇关于插入前如何对密码进行哈希处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!