Skip to content

Custom transformation using @Transform decorator is getting reset #1585

Open
@arun-subramanian-1

Description

@arun-subramanian-1

Description

I have database entity class that i want to serialize and store to db as a record. Before serializing I want Date types to be converted to ISO String and have a custom transformer to do that. When I use instanceToPlain to convert this to plain object I see the transformer is getting invoked but its getting reset back to Date object.

https://github.com/typestack/class-transformer/blob/develop/sample/sample5-custom-transformer/User.ts you can use this itself as an example.

class User {
    id: number

    name: string

    @Type(() => Date)
    @Transform(( { value }) => value.toISOString(), { toPlainOnly: true })
    @Transform(({ value }) => new Date(value), { toClassOnly: true })
      date: Date

    constructor (user: Partial<User>) {
      this.id = user.id ?? 0
      this.name = user.name ?? ''
      this.date = user.date ?? new Date()
    }
  }
const user = new User({})
const obj = instanceToPlain(user)
console.log(typeof obj.date, obj.date instanceof Date) // type should be string but getting as date

The problem seems to be https://github.com/typestack/class-transformer/blob/develop/src/TransformOperationExecutor.ts#L327

finalValue = value[transformKey] === finalValue ? subValue : finalValue;
// final value is string till this point as it got from custom transformation
finalValue = this.transform(subSource, finalValue, type, arrayType, isSubValueMap, level + 1);
// it got converted back to Date object here

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: fixIssues describing a broken feature.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions