0

I am trying to write a function to handle the Get request, here is my code:

  @Get('/find')
  async find(@Param() testname: NameDto) {
    console.log(testname.name);
  }

Here is my dto:

export class NameDto {
  @IsString()
  @ApiProperty({ required: true })
  name: string;
}

I am using the Swagger to test this API : enter image description here When I input a signle a , I got the following response:

{
  "statusCode": 400,
  "message": [
    "name must be a string"
  ],
  "error": "Bad Request"
}

here are more input example :

enter image description here enter image description here

They all return the same response.

Then, I change the find function like this with @Query:

  @Get('/find')
  async find(@Query() testname: NameDto) {
    console.log(testname.name);
  }

here is my input : enter image description here I can have the 200-ok response. Here is another example: enter image description here I enter 1 as the input, and I still can get the 200 response. The dto is not working as expected.

Am I missing something? Any help would be appreciate.

Erika
  • 453
  • 8
  • 23

3 Answers3

1

you are sending nothing in param
you can read in Nestjs document
try this one:

@Get('/find/:testname')
  async find(@Param('testname') testname: NameDto) {
    console.log(testname.name);
  }
Sahand Zeynol
  • 156
  • 2
  • 9
0

You're using query parameters for the url, so you do need to use @Query(). Query parameters will always come in as strings, because that's how express and fastify work. You can enable transform: true and {transformOptions: { enableImplicitConverion: true } } in the ValidationPipe's options and get numbers to show up as actual numbers.

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
  • Hi Jay, I change my code to this : @Get('/find') @UsePipes( new ValidationPipe({ transform: true, transformOptions: { enableImplicitConversion: true }, }), ) async find(@Query() testname: NameDto) { console.log(testname.name); } the dto still not work, there is no different between enter a and 1 – Erika Feb 08 '22 at 23:23
0

you can do something like this it's works for me:

//find-one.dto.ts

import { IsNotEmpty, IsUUID } from 'class-validator';

export class FindOneParams {
  @IsUUID()
  @IsNotEmpty()
  uuid: string;
}
//controller.ts

@Get(':uuid')
find(@Param() { uuid }: FindOneParams) {
    return this.yourService.find(uuid);
  }
//service.ts

find = (uuid: string): Promise<yourType> => ...