ermir
ermir

Reputation: 747

How to set default values on DTO nestJs?

import { IsString, IsNumber, IsOptional, IsUUID, Min, Max } from 'class-validator';
import { Transform } from 'class-transformer';

export class QueryCollateralTypeDto {
  @Transform(({ value }) => parseInt(value))
  @IsNumber()
  @IsOptional()
  page: number;

  @Transform(({ value }) => parseInt(value))
  @IsNumber()
  @IsOptional()
  limit: number;

  @IsString()
  @IsOptional()
  select: string;
}

I want to set default integer values for page and limit and string value for select, (example page value of integer 1, limit value of integer 10, and select value of "field1,field2,...")

Upvotes: 17

Views: 27578

Answers (3)

Lorenzo Regalado
Lorenzo Regalado

Reputation: 243

You have to annotate your controller or method with ValidationPipe with the option transform on true (https://docs.nestjs.com/techniques/validation)

//at the controller level:
@Controller('some_controller')
@UsePipes(new ValidationPipe({ transform: true}))

export class SomeController {
  constructor() {}

  //or at the method level
  @Post()
  @UsePipes(new ValidationPipe({ transform: true}))
  create(
    @Body() someDto: SomeDto,
  ): Promise<someEntity> {
    return this.service.create(someDto);
  }

Upvotes: 3

ermir
ermir

Reputation: 747

Okey i found a solution i guess you just initalize the variables at DTO

import { IsString, IsNumber, IsOptional, IsUUID, Min, Max } from 'class-validator';
import { Transform } from 'class-transformer';

export class QueryCollateralTypeDto {
  @Transform(({ value }) => parseInt(value))
  @IsNumber()
  @IsOptional()
  page: number = 1;

  @Transform(({ value }) => parseInt(value))
  @IsNumber()
  @IsOptional()
  limit: number = 10;

  @IsString()
  @IsOptional()
  select: string = 'name,description';
}

Upvotes: 43

Soroush Ahrari
Soroush Ahrari

Reputation: 593

You can set default values in the service and the function that uses the data like the example below if it is the case for you. If you don't pass any value to the function the default values will be set.

exampleFunction(data: QueryCollateralTypeDto) {
    const { page = 1, limit = 10, select = 'field1' } = data;
    ...
}

Upvotes: 2

Related Questions