简体   繁体   English

类验证器是如何工作的?

[英]How is class-validator works?

i have app with NestJs with server and client separately, in server side I use ValidationPipe and use decorators on DTO classes, for example我有分别带有服务器和客户端的 NestJs 应用程序,在服务器端我使用ValidationPipe并在 DTO 类上使用装饰器,例如

export class SearchDto {
   @IsOptional()
   readonly offset?: string;

   @IsString()
   readonly value: string;

   @IsNumber()
   readonly limit: number;
}

And all works OK, but on the client-side I can't use classes with decorators (its strict rule) and I simply need to use it like type , - const search: SearchDto = await...一切正常,但在客户端我不能使用带有装饰器的类(它的严格规则),我只需要像type一样使用它, - const search: SearchDto = await...

How class-validator ( class-transformer ) works when there is no ValidationPipe over it?当没有ValidationPipe时, class-validator ( class-transformer ) 如何工作? Is it wrapped it as in server side or it fully ignored?是像在服务器端一样包装它还是完全忽略了它? is it calls __decorate and put it inside js bundle?它是调用__decorate并将其放入 js bundle 中吗?

Otherwise I need to write interfaces like this否则我需要写这样的接口

export class SearchDto implements ISearchDto {
   @IsOptional()
   readonly offset?: string;

   @IsString()
   readonly value: string;

   @IsNumber()
   readonly limit: number;
}

export interface ISearchDto {
  offset?: string;
  value: string;
  limit: number;
}

let decorated: SearchDto;
let nonDecorated: ISearchDto;

Thank's for help感谢帮助

If you aren't allowed to use classes with decorators, you may want to look into using class-validator with schemas so that decorators are not necessary.如果不允许将类与装饰器一起使用,您可能需要考虑将类验证器与模式一起使用以便不需要装饰器。

Class-validator works by setting metadata about fields via the decorators it uses, and can only do so much on type alone.类验证器通过它使用的装饰器设置有关字段的元数据来工作,并且只能在类型上做这么多。 The library then reads that metadata and checks it against the current type of the object/field and determines if its conditions are satisfied.然后,库读取该元数据并根据对象/字段的当前类型进行检查,并确定是否满足其条件。 The library is self contained so it doesn't need to go to a server or anything.该库是自包含的,因此不需要访问服务器或任何东西。 If you look at the source code for the ValidationPipe , you can see that Nest is just transforming the object with class-transformer (also known as deserializing) to make the JSON object a JavaScript Class, then runs that class through class-validator , checks the results, and returns, either the instance of the object ( if transform: true is set in the options), or the original payload after it's been validated.如果您查看ValidationPipe源代码,您可以看到 Nest 只是使用class-transformer (也称为反序列化)转换对象,使 JSON 对象成为 JavaScript 类,然后通过class-validator运行该类,检查结果,并返回对象的实例(如果在选项中设置了transform: true ),或者经过验证后的原始有效负载。

The metadata defined by these decorators though can be mimicked through a schema file as described in the first link above.这些装饰器定义的元数据可以通过上面第一个链接中描述的模式文件来模拟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM