How can I validate request body if it's a union type? #2594
Unanswered
gtamas
asked this question in
Questions & Answers
Replies: 1 comment
-
Hi @gtamas You should consider to implement An example // Preparations
export enum MyType {
TYPE_A = 'type-a',
TYPE_B = 'type-b'
}
class A {
myType: MyType.TYPE_A
// And more stuff you need
}
class B {
myType: MyType.TYPE_B,
// And more stuff you need
}
class MyBody {
@Type(
(opts) => {
switch (opts?.object.myType) {
case MyType.TYPE_A:
return A
case MyType.TYPE_B:
return B
default:
return Object
}
},
{
keepDiscriminatorProperty: true,
discriminator: {
property: 'myType',
subTypes: [{ value: A, name: MyType.TYPE_A },{ value: B, name: MyType.TYPE_A }]
}
}
)
@ValidateNested()
realBody: A | B
}
// Implementation
someMethod(
@Param('id') id: string,
@Body() params: MyBody,
): Promise<SomeResult> |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have this situation:
And in controller:
This doesn't work. None of the class validators get executed, I guess that's because the body is not a class, but a union of classes.
Is there any way to make this work? I want the body to be validated either as class A or B.
Beta Was this translation helpful? Give feedback.
All reactions