Runtime Terror
Runtime Terror

Reputation: 6742

Transform the @Body without requiring it in NestJs

What I basically want to do is to parse the date string from the request to a Date object like in this question.

However, this is not my use case because in my case the date is not required. So if I use the solution from the question above it responds with a 400: due must be a Date instance.

This is my DTO:

export class CreateTaskDto {
    @IsDefined()
    @IsString()
    readonly name: string;

    @IsDefined()
    @IsBoolean()
    readonly done: boolean;

    @Type(() => Date)
    @IsDate()
    readonly due: Date;
}

Then in my controller:

@Post('tasks')
async create(
    @Body(new ValidationPipe({transform: true}))
    createTaskDto: CreateTaskDto
): Promise<TaskResponse> {
    const task = await this.taskService.create(createTaskDto);
    return this.taskService.fromDb(task);
}

Post request with this payload is working fine:

{
    "name":"task 1",
    "done":false,
    "due": "2021-07-13T17:30:11.517Z"
}

This request however fails:

{
    "name":"task 2",
    "done":false
}
{
   "statusCode":400
   "message":["due must be a Date instance"],
   "error":"Bad Request"
}

Is it somehow possible to tell nestjs to ignore transformation if there is no date?

Upvotes: 1

Views: 1515

Answers (1)

Jeffrey Mixon
Jeffrey Mixon

Reputation: 13616

@IsOptional()

Checks if given value is empty (=== null, === undefined) and if so, ignores all the validators on the property.

https://github.com/typestack/class-validator#validation-decorators

  @Type(() => Date)
  @IsDate()
  @IsOptional()
  readonly due?: Date;

Upvotes: 3

Related Questions