Currently, I am dealing with MongoDB and subdocuments. MongoDB automatically adds extra fields that cannot be specified in a POST request; they can only be retrieved using a GET request.
To put it simply: different data transfer objects (dto
s).
I am utilizing Swagger and OpenAPI to automatically generate API documentation and I want to avoid redundancy by reusing the same definitions multiple times.
Initially, I considered using 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;
}
(For clarification purposes: this code pertains to an RPG character creator. Points are utilized to purchase attributes, and for compatibility with other functionalities, costs are auto-generated upon document creation.)
The issue here lies in the fact that
FetchAttributeResponseDto extends CreateAttributeRequestDto
- which does not include the extra fields defined in FetchSingleAttributeResponseDto
My inclination would be to - instead of extending CreateAttributeRequestDto
- "copy" it - and use
readonly cou?: FetchSingleAttributeResponseDto
instead
However, this approach goes against the dry principle and just doesn't feel right. Is there a more optimal solution?
Additionally, the created MongoDB Document has supplementary fields like _id, __v, createdAt, updatedAt
- since I don't wish to specify these four keys each time, I contemplated creating another class for them that could be extended - unfortunately, as far as I know, TypeScript does not support multiple inheritance. How would you tackle this issue?