Currently I use the class-transformer package to transform optional values to default values
@IsString()
@IsOptional()
@Transform((description: string) => description || '')
public description: string;
and two problems come up.
So basically I want to create a function transforming the optional value to a default value, my current approach:
function transformValueIfUndefined<TValue>(value: TValue, fallbackValue: TValue): TValue {
if (value === undefined) {
return fallbackValue;
}
return value;
}
Now I could use this function in the Transform decorator
@Transform((description: string) => transformValueIfUndefined(description, ''))
but as you can see this is not worth the effort. Is there a way I can create my own transformation decorator alongside with class-validator and class-transformer to transform optional values?
My custom decorator should look like this
@TransformOptionalValueIfUndefined('')
Decorators are just functions, so why not write your own? Something like this should be enough:
function TransformValueIfUndefined() {
return Transform((description: string) => description || '')
}
@TransformValueIfUndefined()
public description: string;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With