class-transformer icon indicating copy to clipboard operation
class-transformer copied to clipboard

question: Should exposeUnsetFields consider null as well?

Open MasonRhodesDev opened this issue 4 years ago • 1 comments

I was trying to... use class-validator's isOptional in conjuntion with classToPlain to filer out unset / optional fields, but it looks like isOptional and exposeUnsetFields use different logic.

import 'reflect-metadata'
import { plainToClass, classToPlain } from 'class-transformer'
import { IsOptional, validate, ValidationError } from 'class-validator'

class TestClass {
  @IsOptional()
  name?: string
}

function handleErr(errors: ValidationError[]): void {
  if (errors && errors.length > 0) {
    throw new Error('class validation failed')
  }
}

const a = plainToClass(TestClass, { name: undefined })
const b = plainToClass(TestClass, { name: null })

async function runTest() {
  // null is allowed in IsOptional
  await validate(a).then(handleErr)
  await validate(b).then(handleErr)

  console.log(classToPlain(a, { exposeUnsetFields: false }))
  console.log(classToPlain(b, { exposeUnsetFields: false }))
}
runTest().catch(console.error)

The problem: I expected the two to both use IsOptional's implementation to maintain a similar experience across packages.

Is there a way to acheive this with the current package?

And if not, since exposeUnsetValues infers that the value is undefined, would it instead be better to add a flag like exposeOptionalValues for both null and undefined?

*edit: less terrible code snippet

MasonRhodesDev avatar May 06 '21 19:05 MasonRhodesDev

Was stuck with the same problem. It should also consider null to set the default value, not only undefined. I found a workaround using the @Transform decorator. You still need to provide an arbitrary default value for the class attribute though, otherwise it will complain.

  @Expose()
  @Transform(
    ({ value }) =>
      value ||
      "your-default-value",
  )
  logo?: string = "";

MilanMeurrens avatar Jun 12 '24 06:06 MilanMeurrens