Closed scopsy closed 1 year ago
I might be wrong but I think that's due to reflection limitation. We can't tell if that parameter was declared as optional. So if we add some checking for undefined, both
@Query('foo') param: number
@Query('foo') param?: number
will behave the same, right? :thinking:
Exactly @micalevisk, this will behave just the same for both cases. This is why I thought we could introduce an option and to have another check for undefined variables and just ignore them.
as an workaround, you could use @Query() { page, seen }: QueryDTO
@scopsy Have you tried nestjs parsers for primitive types?
async getNotificationsFeed(
@Query('page', ParseIntPipe) page?: number,
@Query('seen', ParseBoolPipe) seen?: boolean
) {
@kirisakiken not yet, will try to check it out 🙏
Let's track this here https://github.com/nestjs/nest/pull/10953
This isn't actually solved.. Passing no value to a query param of type number still results in NaN instead of undefined...
@Hareloo please open another issue instead
This should be fixed when https://github.com/nestjs/nest/pull/12893 is merged. Anyone finding this issue may also be interested in https://github.com/nestjs/nest/issues/13559 which I just opened.
One way that I use to solve the optional boolean value from query string that always return as false:
@IsOptional()
@Transform(({ value }) => {
return [1, '1', true, 'true'].includes(value);
})
active: boolean;
I don't know why but if I set the decorator @IsBoolean()
the value always return as false
Is there an existing issue for this?
Current behavior
We use a validationPipe enabled globally with
transform: true.
The problem is that we have a query param that is set to be optional, like in the snippet below. And the transform converts it to "NaN" instead of leaving it undefined.seen
is always converted to false, even tho I expect it to be undefined or boolean. andpage
is converted toNaN
when the user is not passing a page query param.When looking at the ValidationPipe code, it's clear why it's happening since the type conversion always happens without checking for undefined values.
Minimum reproduction code
https://stackblitz.com/edit/nestjs-typescript-starter-mgxaub?file=src%2Fapp.controller.ts,src%2Fmain.ts
Steps to reproduce
page
query param and the param will be UndefinedExpected behavior
Was expecting it to respect TS annotations and to allow either
undefined
or a transformed numberPackage
Other package
No response
NestJS version
^9.0.0
Packages versions
Node.js version
14.17.6
In which operating systems have you tested?
Other
Should we add a check for undefined in the
transformPrimitive
function? We can also add a new parameter to make sure it doesn't break people code.I can create a PR for this if that's the right direction to solve this.