Federico Fia Sare
Federico Fia Sare

Reputation: 1276

@Get DTO with multiple parameters in 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;
}

Upvotes: 16

Views: 47525

Answers (6)

W.Perrin
W.Perrin

Reputation: 4725

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

Upvotes: 29

Thiago Dantas
Thiago Dantas

Reputation: 73

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 }

Upvotes: 6

Flo H
Flo H

Reputation: 59

You can get multiple params and map them to your dto in this way:

    @Get('/login')
    login(@Param() { userName, password }: LoginUserDto) {
    console.log({ userName});
    console.log({ password });
    return 'OK'
    }

Upvotes: 1

Gimnath
Gimnath

Reputation: 1078

Let's say you need to pass 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';
}

Upvotes: 3

Tejesh Teju
Tejesh Teju

Reputation: 117

@Get('/login/:email/:password')
@ApiParam({name:'email',type:'string'})
@ApiParam({name:'password',type:'string'})
login(@Param() params: string[]) {
    console.log(params)
    return 'OK'
}

Output

{email:<input email >,password:<input password>}

Upvotes: 1

Jesse Carter
Jesse Carter

Reputation: 21207

Nest doesn't support the ability to automatically convert Get query params into an object in this way. It's expected that you would pull out the params individually by passing the name of the param to the @Param decorator.

Try changing your signature to:

login(@Param('userName') userName: string, @Param('password') password: string)

If you want to receive an object instead consider switching to using Post and passing the object in the request body (which makes more sense to me for a login action anyways).

Upvotes: 11

Related Questions