在 NestJs 中转换 @Body 而不需要它
Transform the @Body without requiring it in NestJs
我基本上想做的是将请求中的日期字符串解析为 Date 对象,如 .
但是,这不是我的用例,因为在我的情况下不需要日期。因此,如果我使用上述问题的解决方案,它会以 400 响应:due must be a Date instance
.
这是我的 DTO:
export class CreateTaskDto {
@IsDefined()
@IsString()
readonly name: string;
@IsDefined()
@IsBoolean()
readonly done: boolean;
@Type(() => Date)
@IsDate()
readonly due: Date;
}
然后在我的控制器中:
@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 使用此负载的请求工作正常:
{
"name":"task 1",
"done":false,
"due": "2021-07-13T17:30:11.517Z"
}
但是这个请求失败了:
{
"name":"task 2",
"done":false
}
{
"statusCode":400
"message":["due must be a Date instance"],
"error":"Bad Request"
}
如果没有日期,是否可以通过某种方式告诉 nestjs 忽略转换?
@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;
我基本上想做的是将请求中的日期字符串解析为 Date 对象,如
但是,这不是我的用例,因为在我的情况下不需要日期。因此,如果我使用上述问题的解决方案,它会以 400 响应:due must be a Date instance
.
这是我的 DTO:
export class CreateTaskDto {
@IsDefined()
@IsString()
readonly name: string;
@IsDefined()
@IsBoolean()
readonly done: boolean;
@Type(() => Date)
@IsDate()
readonly due: Date;
}
然后在我的控制器中:
@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 使用此负载的请求工作正常:
{
"name":"task 1",
"done":false,
"due": "2021-07-13T17:30:11.517Z"
}
但是这个请求失败了:
{
"name":"task 2",
"done":false
}
{
"statusCode":400
"message":["due must be a Date instance"],
"error":"Bad Request"
}
如果没有日期,是否可以通过某种方式告诉 nestjs 忽略转换?
@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;