Tea*_*ulo 11 mongodb node.js typeorm class-validator nestjs
创建新用户将忽略来自 create-user.dto.ts
但是,当我更新用户时,它会添加不需要的字段,如下所示:
// update-user.dto.ts
import { IsEmail } from 'class-validator';
import { Address } from '../model/address';
export class UpdateUserDto {
firstName: string;
lastName: string;
@IsEmail(undefined, { message: 'Not a valid e-mail' })
email: string;
username: string;
password: string;
addresses: Address[];
}
Run Code Online (Sandbox Code Playgroud)
这是来自用户服务的更新操作
// user.service.ts
async update(data: UpdateUserDto) {
try {
this.logger.log(data);
const id = '5c6dd9852d4f441638c2df86';
const user = await this.userRepository.update(id, data);
return { message: 'Updated your information' };
} catch (error) {
this.logger.log(error);
throw new HttpException('', HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Run Code Online (Sandbox Code Playgroud)
这是 user.controller.ts
@Patch()
@UsePipes(CustomValidationPipe)
async update(@Body() data: UpdateUserDto) {
return this.userService.update(data);
}
Run Code Online (Sandbox Code Playgroud)
客户端补丁数据:
// Unwanted junk from client
{
"email": "newemail@gmail.com",
"junk": "junk"
}
Run Code Online (Sandbox Code Playgroud)
该email会正确更新,但该行将会有一个新的不必要的属性junk与价值junk
Kim*_*ern 11
我假设你正在使用class-transformer的validate方法在你的CustomValidationPipe。
当您将whitelist选项传递给它时,validate将删除所有未知(-> DTO 类中没有注释)属性:
validate(userUpdate, { whitelist: true })
Run Code Online (Sandbox Code Playgroud)
如果您想抛出验证错误而不是仅仅删除未知属性,您还可以传递该forbidNonWhitelisted选项。
validate(userUpdate, { whitelist: true, forbidNonWhitelisted: true });
Run Code Online (Sandbox Code Playgroud)
在更新的情况下,您可能还想使用skipMissingProperties: true,以便验证不会抛出错误,当 eglastName不是更新的一部分时。
请注意,您应该注释 dto 类中的所有属性,以使验证正常工作:
@IsString()
lastName: string;
@ValidateNested()
@Type(() => Address)
address: Address
Run Code Online (Sandbox Code Playgroud)
不确定何时将此行为/选项添加到 NestJS(也许它是在原始问题和接受的答案之后添加的),但实现未知属性剥离的最佳方法是:
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
}),
);
Run Code Online (Sandbox Code Playgroud)
这就对了。只需确保您whitelist: true的配置中有,您就不会得到任何未知/无效的属性。
您还可以通过设置另一个名为forbidNonWhitelistedto 的属性来完全停止请求true。
更多相关信息:https : //docs.nestjs.com/techniques/validation#stripping-properties
Tea*_*ulo -2
我找到了解决方案:
user.service.ts update() 应该是这样的:
const user = await this.userRepository.create(data);
Run Code Online (Sandbox Code Playgroud)
之前需要添加
await this.userRepository.update(id, user);
Run Code Online (Sandbox Code Playgroud)
这是完整的 user.service.ts update()
async update(data: UpdateUserDto) {
this.logger.log(data);
// added for testing purposes (id should be based on active user)
const id = '5c6ef2c823bf4e3414d65cd0';
const user = await this.userRepository.create(data);
await this.userRepository.update(id, user);
return { message: 'Updated your information' };
}
Run Code Online (Sandbox Code Playgroud)
现在,任何不需要的属性都不会添加到该行中
| 归档时间: |
|
| 查看次数: |
3245 次 |
| 最近记录: |