我想使用 TypeORM 创建一个 NestJS API,并希望将数据库用户映射到发送到客户端的响应模型。我的 UserEntity 只包含一些基本信息
@Entity('User')
export class UserEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@Column()
passwordHash: string;
@Column()
passwordSalt: string;
}
但显然我无法将密码信息发送回客户端。我创建了一个只包含相关信息的响应对象
export interface UserRO {
id: number;
username: string;
}
在调用 GET /users 时,我希望有一组 UserRO。所以我去了
public async find(): Promise<UserRO[]> {
return this.usersRepository.find(); // returning a list of UserEntities
}
不幸的是没有映射,所以响应对象仍然包含密码信息。我用这段代码证明了它
public async find(): Promise<UserRO[]> {
const dbUsers: UserEntity[] = await this.usersRepository.find();
const roUsers: UserRO[] = dbUsers;
console.log(dbUsers);
console.log(roUsers); // still holding the password information
return roUsers;
}
我还使用地图功能添加了一个快速修复
public async find(): Promise<UserRO[]> {
const dbUsers: UserEntity[] = await this.usersRepository.find();
const roUsers: UserRO[] = dbUsers.map((dbUser: UserEntity) => {
return {
id: dbUser.id,
username: dbUser.username,
};
});
console.log(dbUsers);
console.log(roUsers); // not holding the password information anymore
return roUsers;
}
我的问题是:我真的必须手动完成吗?我希望 TypeScript 会删除或忽略所有“未知”键,并且只从匹配的键中获取值。
LEATH
相关分类