Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extend class-transformer Transform function to transform optional values if undefined

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.

  • I have to use this transformation logic multiple times for different types
  • I want to make it testable for the code coverage report

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('')
like image 561
Question3r Avatar asked Jun 08 '26 00:06

Question3r


1 Answers

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;
like image 111
x1n13y84issmd42 Avatar answered Jun 10 '26 06:06

x1n13y84issmd42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!