只是想知道将 NestJS 实体对象转换为 DTO 的最佳方法。
可以说我有以下内容:
import { IsString, IsNumber, IsBoolean } from 'class-validator';
import { Exclude } from 'class-transformer';
export class PhotoSnippetDto {
@IsNumber()
readonly id: number;
@IsString()
readonly name: string;
constructor(props) {
Object.assign(this, props);
}
}
export class Photo {
@IsNumber()
id: number;
@IsString()
name: string;
@IsString()
description: string;
@IsString()
filename: string;
@IsNumber()
views: number;
@IsBoolean()
isPublished: boolean;
@Exclude()
@IsString()
excludedPropery: string;
constructor(props) {
Object.assign(this, props);
}
}
@Controller()
export class AppController {
@Get()
@UseInterceptors(ClassSerializerInterceptor)
root(): PhotoSnippetDto {
const photo = new Photo({
id: 1,
name: 'Photo 1',
description: 'Photo 1 description',
filename: 'photo.png',
views: 10,
isPublished: true,
excludedPropery: 'Im excluded'
});
return new PhotoSnippetDto(photo);
}
}
我期望 ClassSerializerInterceptor 将照片对象序列化到 DTO 并返回如下内容:
{
id: 1,
name: 'Photo 1'
}
但我收到的回复仍然包含所有属性:
{
id = 1,
name = 'Photo 1',
description = 'Photo 1 description',
filename = 'file.png',
views = 10,
isPublished = true
}
我基本上想删除 DTO 中未定义的所有属性。
我知道 ClassSerializerInterceptor 在使用 @Exclude() 时工作得很好,我也希望它也能删除未定义的属性。
我很好奇解决这个问题的最佳方法是什么?我知道我可以做这样的事情:
@Get('test')
@UseInterceptors(ClassSerializerInterceptor)
test(): PhotoSnippetDto {
const photo = new Photo({
id: 1,
name: 'Photo 1',
description: 'Photo 1 description',
filename: 'photo.png',
views: 10,
isPublished: true,
excludedPropery: 'Im excluded'
});
const { id, name } = photo;
return new PhotoSnippetDto({id, name});
}
但是,如果我想在响应中添加另一个属性,我要做的不仅仅是将新属性添加到类中。我想知道是否有更好的“嵌套方式”来做到这一点。