大家好,请教一个关于 'class-validator' 和 PartialType 的问题:
在用 '@nestjs/swagger' 的 PartialType 创建 updateDto 时,我发现了一个问题,PartialType 会为 createDto 里的每个属性添加 @IsOptional() 修饰器,导致前端传入的所有值为 null 的属性都能跳过 'class-validator' 的验证,顺利通过 ValidationPipe
而 undefined 和 null 对于 ORM ,例如 typeorm 有不同的含义,例如:
usersRepository.update({ name: null }) 表示将字段 name 更新为 null
usersRepository.update({ name: undefined }) 表示不对字段 name 进行更新
最终本该 not null 的字段接受了一个 null 值,导致数据库抛错 NOT NULL constraint failed
这应该是一个常见的应用场景吧?没人遇到类似的问题吗?
https://stackoverflow.com/questions/70380391/how-to-mark-certain-fields-as-nullable-or-not-nullable-in-nestjs-request-validat
https://stackoverflow.com/questions/68622366/nestjs-update-is-returning-null-for-other-fields-thereby-giving-validation-issue
附上测试代码,是我实现的方式不对吗?我在网上都搜不到这个问题
https://github.com/yodhcn/mapped-types-example
在用 '@nestjs/swagger' 的 PartialType 创建 updateDto 时,我发现了一个问题,PartialType 会为 createDto 里的每个属性添加 @IsOptional() 修饰器,导致前端传入的所有值为 null 的属性都能跳过 'class-validator' 的验证,顺利通过 ValidationPipe
而 undefined 和 null 对于 ORM ,例如 typeorm 有不同的含义,例如:
usersRepository.update({ name: null }) 表示将字段 name 更新为 null
usersRepository.update({ name: undefined }) 表示不对字段 name 进行更新
最终本该 not null 的字段接受了一个 null 值,导致数据库抛错 NOT NULL constraint failed
这应该是一个常见的应用场景吧?没人遇到类似的问题吗?
https://stackoverflow.com/questions/70380391/how-to-mark-certain-fields-as-nullable-or-not-nullable-in-nestjs-request-validat
https://stackoverflow.com/questions/68622366/nestjs-update-is-returning-null-for-other-fields-thereby-giving-validation-issue
附上测试代码,是我实现的方式不对吗?我在网上都搜不到这个问题
https://github.com/yodhcn/mapped-types-example