简体   繁体   English

控制应用打字稿属性修饰符的顺序?

[英]Controlling the order in which typescript property decorators are applied?

I'm considering writing a validator that checks whether one value is greater than another. 我正在考虑编写一个验证器,以检查一个值是否大于另一个值。 For example purchase price greater than sales price. 例如,购买价格大于销售价格。

But first we would have to make sure that the sales price is valid. 但是首先我们必须确保销售价格有效。 So we might have something like this: 所以我们可能会有这样的事情:

class Product {        

    @IsNumber
    @IsPositive
    purchasePrice: Number;

    @IsNumber
    @IsPositive
    @IsGreaterThan('purchasePrice')
    salesPrice: Number;
}

In this case the @IsNumber and @IsPositive should execute on both properties before the @IsGreaterThan annotation should execute. 在这种情况下, @IsNumber@IsPositive应该在@IsGreaterThan批注执行之前在两个属性上执行。

I'm wondering whether this is something that is simple to implement (Perhaps with some class level metadata) or whether I should just write simple function validators to check this type of stuff. 我想知道这是否是易于实现的(也许带有一些类级别的元数据),还是应该编写简单的函数验证器来检查这种类型的东西。

I'm not a decorator expert, but one thought would be to have validation metadata built into each decorator using a number such that the execution of the validators is sorted by this number. 我不是装饰专家,但我想到的是使用一个数字将验证元数据内置到每个装饰器中,以使验证器的执行按该数字排序。

So for example the @IsGreaterThan validator could have a number 2 assigned, and the others a number 1 and that means that the validator should execute the 1 tagged validators first, and then 2 . 因此,例如,@ IsGreaterThan验证器可以分配一个数字2 ,其他分配器分配一个数字1 ,这意味着该验证器应首先执行1标签的验证器,然后执行2

The decorator should not have a dependency on the usage order. 装饰器不应依赖于使用顺序。 They should be all standalone and work independently. 它们应该都是独立的并且独立工作。

In this case, the @IsGreaterThan should have @IsNumber used internally to ensure the target is a number. 在这种情况下, @IsGreaterThan应该在内部使用@IsNumber以确保目标是数字。

On the other hand, controlling the order is easy. 另一方面,控制顺序很容易。 The closest is applied first. 最接近的被首先应用。 So in your case, you need 因此,您需要

class Product {
  @IsGreaterThan('purchasePrice')
  @IsPositive
  @IsNumber
  salesPrice: number
}

Decorator is just a sugar of a descriptor function, which is a higher order function like this: Decorator只是描述符函数的糖,它是一个高阶函数,如下所示:

function IsNumber(target, key, descriptor) { ... }

So the code above is actually just (pseudo code): 因此,上面的代码实际上只是(伪代码):

class Product {
  salesPrice = IsGreaterThan('puchasePrice')(IsPositive(IsNumber(Product, 'salesPrice')))
}

Since the class syntax is a sugar itself, the code above looks weird as I just trying to show you the underlying concept. 由于class语法本身就是糖,所以上面的代码看起来很奇怪,因为我只是想向您展示基本概念。

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

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