Nestjs Decorator check at least one attribute is accepted

32 Views Asked by At

Maybe I don't understand the DTO, but I want it to check if at least one attribute is sent by the request. How can I do it?

Here is my dto:

//import libs
export class WorkspaceDto {
  @IsString()
  @IsNotEmpty()
  @Transform(({ value }) => value?.trim())
  @ApiProperty()
  @IsOptional()
  id?: string;

  @IsString()
  @IsNotEmpty()
  @Transform(({ value }) => value?.trim())
  @ApiProperty()
  @IsOptional()
  name?: string;

  @IsNotEmpty()
  @IsString()
  @Transform(({ value }) => value?.trim())
  @ApiProperty()
  @IsOptional()
  domain?: string;

  @IsNotEmpty()
  @IsString()
  @Transform(({ value }) => value?.trim())
  @IsOptional()
  @ApiProperty({ enum: WorkspaceStatusEnum, required: false })
  @IsEnum(WorkspaceStatusEnum)
  status?: WorkspaceStatusEnum;
}

For example, if an user sent {}, will it accept and return everything?(which we don't expect). Any way to prevent it?

1

There are 1 best solutions below

0
Ezile Mdodana On

You can create a custom validation pipe like below:

import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';

@Injectable()
export class AtLeastOnePropertyPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    const keys = Object.keys(value);
    if (keys.length === 0) {
      throw new BadRequestException('At least one property must be provided');
    }
    return value;
  }
}

Then, you can use it like this in your controller

import { Controller, Post, Body, UsePipes } from '@nestjs/common';

@Controller('your-endpoint')
export class WorkSpaceController {
  @Post()
  async filter(@Body(new UsePipes(AtLeastOnePropertyPipe)) workspaceDto: WorkspaceDto) {
    // 
  }
}