Modify Request type to include typed body
See original GitHub issueSummary(요약)
Even though there exists a validationMiddleware
that calls plainToClass()
and transforms the body object into a class instance, this class instance is not preserved and will need to be transformed again in the route handler.
Additional Details(추가적인 세부 사항)
What currently exists in the project in the controller is a simple cast const userData: CreateUserDto = req.body;
, but that’s lying to the compiler because userData
is not actually an instance of CreateUserDto
, this can be noticed if the Dto has methods or custom getters or setters. Is this a real concern? Or should we ignore this?
One replacement could be const userData = plainToClass(CreateUserDto, req.body);
, but I was thinking that maybe we can make use of the validationMiddleware
as it calls plainToClass
already.
What do you think?
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (3 by maintainers)
Top GitHub Comments
@MuathAmer
Oh thank you very much. We will test and review your suggestions, but I think your suggestions are really good. If you leave a pull request, we will improve it quickly.
@ljlm0402 There is no reason it won’t work as far as I see. Is your concern about the type safety of
validatedBody: CreateUserDto
when settingskipMissingProperties = true
? If so, I think that’s fine as long as the programmer realizes that some properties in the DTO (validatedBody
) are optional, and this can also apply to the implementation as so:Notice the
?
optional operator above.Or you can have separate
CreateUserDto
andUpdateUserDto
, and the programmer might use class-validator’sIsOptional()
decorator or settingskipMissingProperties = true
, both are valid options forUpdateUserDto
, but at this point that’sclass-validator
’s knowledge.