0

我的数据库列是双精度类型(来自Postgres 文档

双精度 8 字节可变精度,不精确 15 位小数精度

使用类验证器我想进行精度检查

@IsNumber()
/* precision check */
public myValue: number;

IsDecimal装饰器在这里可能会有所帮助,所以可以@IsDecimal({ decimal_digits: '15' })做到这一点。我必须将这个装饰器用于多个字段,有没有办法扩展现有的装饰器并传入decimal_digits选项?我认为重新发明轮子没有意义。如果我可以继承验证但将精度设置为小于或等于 15那就太好了。

目前我创建了自己的装饰器

@ValidatorConstraint()
class IsDoublePrecisionConstraint implements ValidatorConstraintInterface {
    public validate(value: any): boolean {
        if (typeof value === 'number') {
            if (value % 1 === 0) {
                return true;
            }

            const valueText: string = value.toString();
            const valueSegments: string[] = valueText.split('.');
            const decimalDigits: string = valueSegments[1];

            return decimalDigits.length <= 15;
        }

        return false;
    }

    public defaultMessage(args: ValidationArguments): string {
        return `${args.property} must have less than or equal to 15 decimal digits.`;
    }
}

export function IsDoublePrecision() {
    return (object: Record<string, any>, propertyName: string) => {
        registerDecorator({
            target: object.constructor,
            propertyName,
            validator: IsDoublePrecisionConstraint,
        });
    };
}

但我不确定这个是否能够处理所有案件。

提前致谢

4

1 回答 1

1

我没有找到任何关于扩展现有装饰器的示例class-validator,但IsDecimal只是一个普通的属性装饰器,那么我们可以将它用作属性装饰器。

我的想法是创建一个“普通”属性装饰器并IsDecimal使用选项调用这个装饰器decimal_digits

// function as a const
export const IsDoublePrecision = () => { // use decorator factory way
  return (target: object, key: string) => { // return a property decorator function
    IsDecimal({ decimal_digits: '15' })(target, key); // call IsDecimal decorator
  }
}

用法:

@IsNumber()
/* precision check */
@IsDoublePrecision()
public myValue: number;
于 2020-04-15T03:25:50.947 回答