Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom transformation using @Transform decorator is getting reset #1585

Open
arun-subramanian-1 opened this issue Aug 3, 2023 · 0 comments
Labels
type: fix Issues describing a broken feature.

Comments

@arun-subramanian-1
Copy link

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
@arun-subramanian-1 arun-subramanian-1 added status: needs triage Issues which needs to be reproduced to be verified report. type: fix Issues describing a broken feature. labels Aug 3, 2023
@diffy0712 diffy0712 removed the status: needs triage Issues which needs to be reproduced to be verified report. label May 9, 2024
@diffy0712 diffy0712 self-assigned this May 9, 2024
@diffy0712 diffy0712 removed their assignment Dec 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: fix Issues describing a broken feature.
Development

No branches or pull requests

2 participants