Home > Mobile >  How to set default values on DTO nestJs?
How to set default values on DTO nestJs?

Time:07-22

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,...")

CodePudding user response:

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

CodePudding user response:

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';
}
  • Related