在Nest.JS API和React Web之间传递数据的正确方式是什么



我开始学习Nest.JS,我选择了TypeORM作为后端ORM和前端React(如果重要的话(。

我想知道,什么是最好的沟通方式(发送数据(。目前,我有一个TypeORM实体:

@Entity({
schema: 'security',
name: 'user',
})
export class UserEntity extends BaseEntity {
@PrimaryGeneratedColumn()
public id: number;
@Column({
nullable: false,
unique: true,
})
public email: string;
@Column({
nullable: false,
})
public firstName: string;
@Column({
nullable: false,
})
public lastName: string;
...
}

数据库数据提取服务:

@Injectable()
export class UserService {
constructor(private hashService: HashService) {}
public create = async (user: UserCreateDto): Promise<UserEntity> => {
const { password, ...data } = user;
return UserEntity.create({
password: await this.hashService.hash(user.password),
...data,
}).save();
};
public findById = async (id: number): Promise<UserEntity> => {
return UserEntity.findOne({
where: {
id,
},
relations: ['role'],
});
};
}

控制器:

@Controller('user')
export class UserController {
public constructor(private userService: UserService) {}
@Post()
async create(@Body() body: UserCreateDto): Promise<UserResponseDto> {
return this.userService.create(body);
}
@Get(':id')
async findById(
@Param('id', ParseIntPipe) id: number,
): Promise<UserResponseDto> {
return this.userService.findById(id);
}
}

使用UserCreateDto进行验证工作正常,但UserResponseDto给了我一些问题:

@Exclude()
export class UserResponseDto {
@Expose()
public id: number;
@Expose()
public email: string;
@Expose()
public firstName: string;
@Expose()
public lastName: string;
...
}

即使像password这样的字段没有出现在这个dto中,我的邮递员响应中也有实体的所有字段。我试图隐式地@Exclude password字段,但它也不起作用。

我尝试添加GlobalInterceptor:

app.useGlobalInterceptors(
new ClassSerializerInterceptor(app.get(Reflector), {
strategy: 'excludeAll',
excludeExtraneousValues: true,
exposeDefaultValues: true,
exposeUnsetFields: true,
enableImplicitConversion: true,
}),
);

但它要么使响应正文为空,要么返回所有字段(尝试了不同的选项(。

我应该如何配置序列化,还是应该执行其他操作?

您在结构上返回了一个与UserResponseDto类似的对象,但这不会使ClassSerializerInterceptor工作,因为class-transformer(拦截器使用的(需要有一个类实例,这样它就可以读取类的元数据来知道返回什么。您要么需要手动将检索到的实体映射到DTO,要么需要使用类似自动映射器的解决方案。

最新更新