gpt4 book ai didi

typescript - Typescript 混合类上的类验证器装饰器

转载 作者:行者123 更新时间:2023-12-04 15:28:25 25 4
gpt4 key购买 nike

在我的项目中,我有一个具有许多属性的大对象。每个属性都有自己独特的验证,这些验证使用 class validator decorators 对其执行。 .该类的每个属性都被描述为一个 mixin。但是,我注意到当将 mixin 应用于基类时,只有最后传递的 mixin 才会运行其装饰器以进行验证。

例如,我们有:

export class Property {
public async validate (): Promise<string[]> {
const result = await validate(this)
return result
}
}

export class Name extends Property {
@IsDefined()
@IsString()
@Length(5, 255)
name: string
}

export class Description extends Property {
@IsDefined()
@IsString()
@Length(16, 1000)
description: string
}

每个属性在进行单元测试时都会正确验证自身。

当创建继承自 mixins 的类时,我正在执行以下操作:

/**
* Applies the mixins to a class. Taken directly from the Typescript documentation.
*/
function applyMixins (derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name))
})
})
}

export class Foo {
public async validate (): Promise<any> {
const result = await validate(this)
return result
}
}

export interface Foo extends Name, Description { }
applyMixins(Foo, [Name, Description])

但是,当创建 Foo 的实例并在该实例上调用 .validate 时,我们只会收到 Description 的错误。

是否有一些不同的方法来应用混合以验证所有混合属性?

最佳答案

发生这种情况是因为 сlass-validator 使用原型(prototype)来检测验证规则,我们需要将规则复制到派生 ctor 的原型(prototype)。

我们可以这样做:

/**
* Applies the mixins to a class, but with class validator constraints.
*/
function applyMixinsWithValidators (derivedCtor: any, baseCtors: any[]) {
const metadata = getMetadataStorage() // from class-validator

// Base typescript mixin implementation
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name))
})
})

baseCtors.forEach(baseCtor => {
// Get validation constratints from the mixin
const constraints = metadata.getTargetValidationMetadatas(baseCtor.prototype.constructor, '')

for (const constraint of constraints) {
// For each constraint on the mixin
// Clone the constraint, replacing the target with the the derived constructor
let clone = {
...constraint,
target: derivedCtor.prototype.constructor
}
// Set the prototype of the clone to be a validation metadata object
clone = Object.setPrototypeOf(clone, Object.getPrototypeOf(constraint))
// Add the cloned constraint to class-validators metadata storage object
metadata.addValidationMetadata(clone)
}
})
}

关于typescript - Typescript 混合类上的类验证器装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61779822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com