【问题标题】:Validate DTO in controller when passing data to service将数据传递给服务时验证控制器中的 DTO
【发布时间】:2020-09-27 16:35:12
【问题描述】:

我正在尝试在 PUT 请求中插入验证(以更新存储在 MongoDB 中的一些数据):

DTO:

export enum reportFields {
    'startDate',
    'targetDateOfCompletion',
    'duration',
}


export class updateScheduleDto {
    @IsOptional()
    @IsString()
    readonly frequency?: string;

    @IsOptional()
    @IsArray()
    @IsEmail({}, { each: true })
    @IsString({ each: true })
    readonly emails?: string[];

    @IsOptional()
    @IsEnum(reportFields, { each: true })
    @IsArray()
    @IsString({ each: true })
    readonly reportFields?: string[];

    @IsOptional()
    @Type(() => Number)
    @IsNumber()
    updatedAt?: number;
}

控制器:

@Put('reports/:id/schedule')
async updateScheduleData(
    @Param('id') id: string,
    @Body(new ValidationPipe()) updateData: updateScheduleDto,
) {
    return this.reportService.updateScheduleData(id, updateData);
}

服务:

 async updateScheduleData(id: string, updateData: updateScheduleDto) {
        try {
            updateData.updatedAt = this.utils.getCurrentTime();
            const newData = await this.reportScheduleModel.findByIdAndUpdate(
                id,
                updateData,
                {
                    new: true,
                },
            );

            console.log(`Data has been updated to ${newData}`);
            return newData;
        } catch (error) {
            throw new Error('>>>' + error);
        }
    }

但验证无法通过密钥进行。如果我在 body 对象中传递了一个无效的键(如下所示),即使程序执行没有任何错误,我该如何解决这个问题?我错过了什么?

{
    "emaaaalls":["randomemail123@gmail.com"]
}

【问题讨论】:

  • 我遇到了完全相同的问题。我的配置与其他答案相同。我不知道为什么,但永远不会抛出错误 - 甚至在 findByIdAndUpdate 的 catch 事件中也没有。

标签: mongodb typescript validation nestjs dto


【解决方案1】:

您需要将选项{ forbidUnknownValues: true } 传递给ValidationPipe。这将使class-validator在传入未知值时抛出错误。You can read through the options here

【讨论】:

  • 我现在添加了。但我仍然面临同样的问题。
  • 你可能还需要forbidNonWhitelisted ass 另一个选项
  • 也试过了。尽管如此,程序执行时不会抛出任何错误。我哪里错了?
  • 更改后是否重新编译服务器?你是如何重新开始的?
  • 是的,每次更改后服务器都会自动重启
【解决方案2】:

您可以在ValidationPipe 选项中设置whitelist: true

设置为 true 时,这将自动删除未列入白名单的属性(那些在验证类中没有任何装饰器的属性)。

你可以阅读更多关于这个https://docs.nestjs.com/techniques/validation#stripping-properties

【讨论】:

    猜你喜欢
    • 2013-10-06
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多