[ ] Regression
[ ] Bug report
[x] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
When using a DTO which will be passed as query (Query decorator), all its properties get initially passed as string. When applying type validation with class-validator decorators (IsInt as example), it fails because of the missing type conversion.
You could say it is as expected since query params are always strings. Still its inconsistent since it would work when using a POST and the Body decorator.
page.dto.ts
export class PageDto {
@IsInt()
readonly pageIndex: number;
}
sample.controller.ts
@Controller('sample')
export class SampleController {
@Get()
getPage(@Query() page: PageDto): any {
// ...
}
}
It really took me some time to understand the problem here. It might me intended but i think there should be at least a hint in the documentation.
Nest version: 5.0.0
For Tooling issues:
- Node version: 10.3.0
- Platform: Windows 8.1
Others:
@DavidVollmers hmmm, for me it's normal behaviour, you should be aware that it won't be changed auto-magically without your work for that, you should use Pipes for that, and this is explained in documentation here: https://docs.nestjs.com/pipes and use https://github.com/typestack/class-transformer for that what you're trying to achieve.
@DavidVollmers you can use IsNumberString
from class-validator
in your Query params validation
@zMotivat0r It's not a very good workaround because sometimes you want to define @Max
of the number, but if its a "NumberString" the @Max
isn't working
@yogevlahyani true, this would work though. (with validation/transform pipe)https://docs.nestjs.com/techniques/validation
export class UserQueryDto{
@IsNumber()
@Max(20)
@Transform(value => Number(value))
page: number = 1;
}
@yogevlahyani true, this would work though. (with validation/transform pipe)https://docs.nestjs.com/techniques/validation
export class UserQueryDto{ @IsNumber() @Max(20) @Transform(value => Number(value)) page: number = 1; }
Exactly what i was looking for. Thanks @grtrapma
For those, who is confused as I was, from where this Transform decorator is imported: it is contained in class-transformer package.
@DavidVollmers how can you get DTO into swagger, imagine dto with 10 params, then swagger geerated code will be nightmare.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
@yogevlahyani true, this would work though. (with validation/transform pipe)https://docs.nestjs.com/techniques/validation