在我的项目中,我有一个带有许多属性的大对象。每个属性都有自己独特的验证,使用class validator decorators对它进行验证。该类的每个属性都描述为一个混合。但是,我注意到,当将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的错误。
是否有其他方法可以应用mixins来对所有混合属性进行验证?
答案 0 :(得分:2)
之所以会这样,是因为lass-validator使用原型来检测验证规则,因此我们需要将规则复制到派生ctor的原型中。
我们可以这样做:
/**
* 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)
}
})
}