控制应用 typescript 属性装饰器的顺序?

Ole*_*Ole 1 javascript validation decorator typescript typescript-decorator

我正在考虑编写一个验证器来检查一个值是否大于另一个值。例如购买价格大于销售价格。

但首先我们必须确保销售价格有效。所以我们可能有这样的事情:

class Product {        

    @IsNumber
    @IsPositive
    purchasePrice: Number;

    @IsNumber
    @IsPositive
    @IsGreaterThan('purchasePrice')
    salesPrice: Number;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,@IsNumber@IsPositive应该在@IsGreaterThan注释执行之前在两个属性上执行。

我想知道这是否易于实现(也许有一些类级别的元数据),或者我是否应该只编写简单的函数验证器来检查这种类型的东西。

我不是装饰器专家,但有人认为使用数字将验证元数据内置到每个装饰器中,以便验证器的执行按此数字排序。

因此,例如 @IsGreaterThan 验证器可以2分配一个数字,其他人分配一个数字1,这意味着验证器应该首先执行1标记的验证器,然后2.

uni*_*nal 5

装饰器不应依赖于使用顺序。它们应该都是独立的并独立工作。

在这种情况下,@IsGreaterThan应该在@IsNumber内部使用以确保目标是一个数字。

另一方面,控制订单很容易。首先应用最接近的。所以在你的情况下,你需要

class Product {
  @IsGreaterThan('purchasePrice')
  @IsPositive
  @IsNumber
  salesPrice: number
}
Run Code Online (Sandbox Code Playgroud)

装饰器只是描述符函数的一个糖,它是一个像这样的高阶函数:

function IsNumber(target, key, descriptor) { ... }
Run Code Online (Sandbox Code Playgroud)

所以上面的代码其实只是(伪代码):

class Product {
  salesPrice = IsGreaterThan('puchasePrice')(IsPositive(IsNumber(Product, 'salesPrice')))
}
Run Code Online (Sandbox Code Playgroud)

由于class语法本身就是一种糖,上面的代码看起来很奇怪,因为我只是想向您展示基本概念。