Erika
Erika

Reputation: 601

How to use Get request with DTO in NestJs?

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.

Upvotes: 0

Views: 5638

Answers (3)

ARGOUBI Sofien
ARGOUBI Sofien

Reputation: 76

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> => ...

Upvotes: 0

Sahand Zeynol
Sahand Zeynol

Reputation: 331

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);
  }

Upvotes: 1

Jay McDoniel
Jay McDoniel

Reputation: 70111

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.

Upvotes: 0

Related Questions