class-validator
在验证子类型时如何变得更严格 - 具体来说,拒绝无效的鉴别器值,而不是自动查看数组内部?
考虑以下代码:
import 'reflect-metadata';
import { Equals, ValidateNested, validateOrReject } from 'class-validator';
import { plainToClass, Type } from 'class-transformer';
class Base {
type: string;
value: string;
}
class Derived1 extends Base {
@Equals('value1')
value: string;
}
class Derived2 extends Base {
@Equals('value2')
value: string;
}
class Data {
@ValidateNested()
@Type(() => Base, {
keepDiscriminatorProperty: true,
discriminator: {
property: 'type',
subTypes: [
{ value: Derived1, name: 'derived1' },
{ value: Derived2, name: 'derived2' },
],
},
})
stuff: Base;
}
const validate = async (data: unknown) => {
const instance = plainToClass(Data, data);
await validateOrReject(instance);
};
(async () => {
validate({ stuff: { type: 'derived1', value: 'value1' } }); // (1) passes as expected
validate({ stuff: { type: 'derived2', value: 'value2' } }); // (2) passes as expected
validate({ stuff: { type: 'derived3', value: 'value3' } }); // (3) how can I get this to throw?
validate({ stuff: [{ type: 'derived1', value: 'value1' }] }); // (4) how can I get this to throw?
validate({ stuff: [{ type: 'derived1', value: 'value2' }] }); // (5) this throws, expecting 'value' to equal 'value1'
})();
在 (3) 中,似乎对传递class-validator
的无效字段非常满意。type
也许它实际上class-transformer
应该被扔在这里?
在(4)中,我实际上很惊讶这没有任何问题。我可以强制class-validator
/class-transformer
不自动验证每个数组元素,就好像它是一个Base
?