请求/响应的DTO不同



我正在处理MongoDB和子文档。MongoDB生成无法在POST中设置的附加字段,只能获取它们。换句话说:不同的dtos.

我正在使用Swagger和OpenAPI自动生成API文档,并且不想多次使用相同的定义来重复我自己(干(。

我的第一个想法是extend:

export class CreateSingleAttributeRequestDto {
@ApiProperty({
example: 10,
description: 'Attribute Value',
format: 'integer',
})
@IsInt()
readonly value: number = SINGLE_ATTRIBUTE_VALUE_DEFAULT;
}
export class FetchSingleAttributeResponseDto extends CreateSingleAttributeRequestDto {
@ApiProperty({
example: 30,
description: 'GENERATED. Cost of the attribute.',
format: 'integer',
})
@IsInt()
readonly ap?: number;
}
export class CreateAttributeRequestDto {
readonly attributes?: {
readonly cou?: CreateSingleAttributeRequestDto;
readonly sgc?: CreateSingleAttributeRequestDto;
}
}
export class FetchAttributeResponseDto extends CreateAttributeRequestDto {
@ApiProperty({
example: 98,
description: 'GENERATED. Sum of all values of the 8 attributes',
format: 'integer',
})
@IsInt()
readonly total?: number;
}

(如果你在理解语义方面有问题:这是RPG角色创建者的代码。你为你的属性和与其他功能的兼容性付费,那么在文档上创建时会自动生成成本。(

问题是:FetchAttributeResponseDto extends CreateAttributeRequestDto-在FetchSingleAttributeResponseDto中没有设置附加字段

我的想法是——而不是扩展CCD_ 5-";复制";而是使用readonly cou?: FetchSingleAttributeResponseDto

这违反了枯燥的原则,而且感觉不对。有更好的解决方案吗?

另外:create MongoDB Document有额外的字段,比如_id, __v, createdAt, updatedAt——因为我不想每次都写这4个键,所以我想为我扩展的那些键创建一个额外的类——不幸的是,TS不支持多继承afaik。你将如何实现这一点?

您可以为此使用@nestjs/mapped-type。在扩展时使用OmitTypePickTypePartialType,如:

export class UpdateUserInput extends PartialType(CreateUserInput) {}

更多信息请访问此官方博客。

最新更新