Nest: How to validate ONE param in query nestjs?

Created on 1 May 2020  路  5Comments  路  Source: nestjs/nest

I need to validate only one param in query.

What I have now:

  @Get('status')
  getStatus(@Query() token: string): IStatusResponse {
    if (!token) {
      throw new HttpException('Token param is empty', HttpStatus.BAD_REQUEST);
    }
    const response = this.service.getStatus(token);
    if (response) {
      return response;
    }
    throw new HttpException('Data not found.', HttpStatus.NOT_FOUND);
  }

How I wish it was:

  @Get('status')
  @IsNotEmptyParam('token', 'Token param is empty', HttpStatus.BAD_REQUEST)
  getStatus(@Query() token: string): IStatusResponse {
    const response = this.service.getStatus(token);
    if (response) {
      return response;
    }
    throw new HttpException('Data not found.', HttpStatus.NOT_FOUND);
  }

or something

And what else can be improved in this code?

thx!

needs triage question 馃檶

Most helpful comment

I think this is already implemented with the auto validation feature of nest 7.
In the documentation, there is already something similar to what you are looking for.
The example is for param but I will assume it will be the same for query params as well.

@Get(':id') findOne(@Param() params: FindOneParams) { return 'This action returns a user'; }

`import { IsNumberString } from 'class-validator';

export class FindOneParams {
@IsNumberString()
id: number;
}`
https://docs.nestjs.com/techniques/validation#auto-validation

All 5 comments

What is @IsNotEmptyParam()? Couldn't you make this kind of logic work with a pipe?

Please use Discord as we are using GitHub to track bugs and enhancements.

What is @IsNotEmptyParam()? Couldn't you make this kind of logic work with a pipe?

Please use Discord as we are using GitHub to track bugs and enhancements.

this is my fiction about how I would like

As I said, what you're looking for is doable in a pipe. This isn't really an enhancement to the framework. If you need more guidance, please ask on Discord

I think this is already implemented with the auto validation feature of nest 7.
In the documentation, there is already something similar to what you are looking for.
The example is for param but I will assume it will be the same for query params as well.

@Get(':id') findOne(@Param() params: FindOneParams) { return 'This action returns a user'; }

`import { IsNumberString } from 'class-validator';

export class FindOneParams {
@IsNumberString()
id: number;
}`
https://docs.nestjs.com/techniques/validation#auto-validation

thanks everyone

Was this page helpful?
0 / 5 - 0 ratings