Search code examples
node.jsvalidationnestjsdefault-valueclass-validator

Define random default value in class-validator for each request in NestJS


How can I specify a field to have a default value for each request? not for all requests. I know how can I pass the default value for a field in the class-validator:

export class CreateUserDto {
  @IsString()
  username = "static-username";
}

But this piece of code would cause a static default value for all requests, But I need to generate a username for each request. Note: I know I can handle these kinds of problems/issues in the controller. but I think it is better to handle it in the validator. in the following example, you can see what i mean by handling the random value in the controller:

class CreateUserDto {
  @IsOptional()
  @IsString()
  username?: string;
}

/* ... */
@Post('/users')
async createUser(@Body user: CreateUserDto) {
  if (user.username === undefined) {
    user.username = `random-${Math.random()}`
  }
}
/* ... */

Solution

  • It's not true that you can only send back static values in the DTO. You can simply do this:

    class CreateUserDto {
      @IsOptional()
      @IsString()
      username: string = `random-${Math.random()}`
    }
    
    /* ... */
    @Post('/users')
    async createUser(@Body(new ValidationPipe({ whitelist: true })) user: CreateUserDto) {
      console.log(user.username) // random-0.8392092045730202
    }
    /* ... */
    

    Maybe your issue while testing was that you are not enabling the ValidationPipe: @Body user: CreateUserDto has to be @Body(ValidationPipe) user: CreateUserDto. With whitelist: true you will also remove all not defined key value pairs which is quite helpful.