创建自定义验证装饰器:它是如何工作的?

Create custom validation decorator : how it works?

我想创建一个自定义装饰器,但我想我不太明白它是如何工作的! 起初我开始验证所有非空字段。

E.G :

    @AllowNull(false)
    @Validate({
        notNull: {
            msg: 'zip code is required',
        },
    })
    @Column({
        type: DataType.STRING,
    })
    zip_code: string;

但后来我想“DRY 原则在那里并不适用,您如何制作自定义验证器?”

我尝试了一些东西class-validator就是其中之一。但是我没有设法让它按预期工作。

当发送带有 null zip_code 的请求时,未触发自定义验证装饰器,因为此字段被设置为空到此记录的数据库中(在创建或更新时)

我现在能做的最好的事情是

//required.ts
export function required(field) {
    return {
        notNull: {
            msg: `${field} is required.`,
        },
    };
}

我只是return@Validate需要输出正确信息的对象

    @Validate(required('zip_code'))
    @Column({
        type: DataType.STRING,
    })
    zip_code: string;

几天前我开始使用 Nest。我不是很熟悉它。 我很确定有一个简单的方法。这就是为什么我在这里问这个问题

谢谢

解决方案只是在我的服务中使用 'class-validator' 中的验证方法

//required.ts
import { registerDecorator } from 'class-validator';

export function Required(property: string) {
    return function (object, propertyName: string) {
        registerDecorator({
            name: 'isRequired',
            target: object.constructor,
            propertyName: propertyName,
            constraints: [property],
            // Not the best way but it works, i'll update the answer later ;)
            options: {
                message: '$property is required',
            },
            validator: {
                validate(value: any) {
                    return value !== null;
            },
        });
    };
}
// CompanyService.ts
    create(createCompanyDto: CreateCompanyDto) {
// Instead of Model.create use Model.build then Model.save after validate
        const company = Company.build(createCompanyDto);
        return validateOrReject(company, {
            validationError: { target: false },
        })
            .then(() => company.save())
            .catch((errors) => errors);
    }
// company.entity.ts
// there you can call the decorator
    @Required('city')
    @Column({
        type: DataType.STRING,
    })
    city: string;

我的错误是使用 Model.create 或 Model.update 而不是构建然后验证