我正在做一个nestjs应用程序,在postgress中使用typeorm
我试图在我的 JSON 返回中排除password
和accessToken
列,但是在创建新用户时它不起作用。我尝试使用@UseInterceptors(ClassSerializerInterceptor)
,但没有奏效。
这是我的代码片段。
用户实体.ts
import { Exclude } from 'class-transformer';
import { IsEmail } from 'class-validator';
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
import { UserRoles } from './user.interface';
@Entity()
export class UserEntity {
@PrimaryGeneratedColumn()
userId: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column({ unique: true })
@IsEmail()
email: string;
@Column()
role: UserRoles;
@Exclude({ toPlainOnly: true })
@Column()
password: string;
@Column({ default: false })
isActive: boolean;
@Exclude({ toPlainOnly: true })
@Column()
accessToken: string;
用户控制器.ts
@Post()
@UseInterceptors(ClassSerializerInterceptor)
async signup(@Body(new ValidationPipe({transform: true})) user: CreateUserDto): Promise<User> {
if (user.password == user.verifyPassword) {
const newuser = await this.userService.createUser(user);
if (newuser.userId) {
await this.mailService.sendVerificationEmail(newuser);
}
return newuser;
} else {
throw new HttpException(
MESSAGES.PASSWORD_NOTMATCH_ERROR,
HttpStatus.BAD_REQUEST,
);
}
}
用户服务.ts
async createUser(user: CreateUserDto): Promise<User> {
user.password = await bcrypt.hash(user.password, 12);
user.accessToken = crypto.randomBytes(40).toString('hex');
user.accessTokenExpiry = new Date(
new Date().setDate(new Date().getDate() + 1),
);
return this.userRepository.save(user);
}
main.ts
import { ClassSerializerInterceptor, ValidationPipe } from '@nestjs/common';
import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));
await app.listen(process.env.PORT);
}
bootstrap();
如果我错过了什么或做错了什么,请告诉我