0

I have a NestJS controller like this:

@Put('/:id')
  updateLocalityInfo(
    @Query('type') type: string,
    @Body() data: EditLocalityDto,
    @Body('parentId', ParseIntPipe) parentId: number,
    @Param('id', ParseIntPipe) id: number,
  ) {
    console.log(data);
    return this.localitiesService.updateLocalityInformation(
      type,
      data,
      id,
      parentId,
    );
  }

in which I'm getting a bunch of data. however, I'm having issues with the Dto and the parentId variable. When I call this route the parentId seems to be part of the Dto-data. the console.log shows

{ name: 'exampleName', parentId: '1' }

my dto only has a name:

import { ApiProperty } from '@nestjs/swagger';

export class EditLocalityDto {
  @ApiProperty()
  name: string;
}

I want to get rid of the parentId being part of the dto-data. how do I do that in general

Vladyslav Zavalykhatko
  • 15,202
  • 8
  • 65
  • 100
Exo
  • 237
  • 1
  • 2
  • 13

1 Answers1

0

You could think of one of 2 approaches

Solution 1

Exclude the redundant property using TS from the DTO:

@Put('/:id')
  updateLocalityInfo(
    @Query('type') type: string,
    @Body() { parentId: _, ...data }: EditLocalityDto,
    @Body('parentId', ParseIntPipe) parentId: number,
    @Param('id', ParseIntPipe) id: number,
  ) {
    console.log(data);
    return this.localitiesService.updateLocalityInformation(
      type,
      data,
      id,
      parentId,
    );
  }

Solution 2

Instead of excluding the property, you could add it to the DTO itself and validate it there:

@Put('/:id')
  updateLocalityInfo(
    @Query('type') type: string,
    @Body() { parentId, ...data }: EditLocalityDto,
    @Param('id', ParseIntPipe) id: number,
  ) {
    console.log(data);
    return this.localitiesService.updateLocalityInformation(
      type,
      data,
      id,
      parentId,
    );
  }

///

import { ApiProperty } from '@nestjs/swagger';

export class EditLocalityDto {
  @IsInt()
  parentId: number

  @ApiProperty()
  name: string;
}

I'd prefer the later

Vladyslav Zavalykhatko
  • 15,202
  • 8
  • 65
  • 100