Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Get DTO with multiple parameters in NestJs

Tags:

nestjs

I'm trying to create a controller action in NestJS accessible via GET HTTP request which receives two params but they are undefined for some reason.

How to fix it?

@Get('/login')
login(@Param() params: LoginUserDto) {
  console.log(params)
  return 'OK'
}
import { ApiModelProperty } from '@nestjs/swagger';

export class LoginUserDto {
  @ApiModelProperty()
  readonly userName: string;

  @ApiModelProperty()
  readonly password: string;
}
like image 913
Federico Fia Sare Avatar asked Nov 22 '18 00:11

Federico Fia Sare


3 Answers

In Browser

localhost:3001/Products/v1/user2

Controller like this:

@Controller('Products')
export class CrashesController {
  constructor(private readonly crashesService: CrashesService) { }

  @Get('/:version/:user')
  async findVersionUser(@Param('version') version: string, @Param('user') user: string): Promise<Crash[]> {
    return this.crashesService.findVersionUser(version, user);
  }
}
like image 105
W.Perrin Avatar answered Oct 28 '22 07:10

W.Perrin


Let's say you need to pass a one required parameter named id you can send it through header params, and your optional parameters can be sent via query params;

 @Get('/:id')
  findAll(
    @Param('id') patientId: string,
    @Query() filter: string,
  ): string {
    console.log(id);
    console.log(filter);

    return 'Get all samples';
  }
like image 41
Gimnath Avatar answered Oct 28 '22 08:10

Gimnath


Right now i am using nestJs on 7.0.0 and if you do this:

@Get('/paramsTest3/:number/:name/:age')
  getIdTest3(@Param() params:number): string{
    console.log(params);
    return this.appService.getMultipleParams(params);
  }

the console.log(params) result will be(the values are only examples):

{ number:11, name: thiago, age: 23 }

i hope that after all that time i've been helpful to you in some way !

like image 34
Thiago Dantas Avatar answered Oct 28 '22 06:10

Thiago Dantas