typestack / class-transformer

Decorator-based transformation, serialization, and deserialization between objects and classes.
MIT License
6.81k stars 500 forks source link

fix: Multiple Getter Calls in class-transformer #1707

Open JHyeok opened 4 months ago

JHyeok commented 4 months ago

Description

I am experiencing an issue with class-transformer in my NestJS project where getter methods are being called multiple times. This issue arises when using the instanceToPlain method.

Minimal code-snippet showcasing the problem

import { User } from '../domain/user.entity';
import { Exclude, Expose } from 'class-transformer';

export class UserResponseDto {
  @Exclude() private readonly _firstName: string;
  @Exclude() private readonly _lastName: string;

  constructor(user: User) {
    console.log('Constructor called');
    this._firstName = user.firstName;
    this._lastName = user.lastName;
  }

  @Expose()
  get firstName(): string {
    console.log('First Name getter called');
    return this._firstName;
  }

  @Expose()
  get lastName(): string {
    console.log('Last Name getter called');
    return this._lastName;
  }
}

// Usage example
const user = new User(); // Assume this is populated with data
const userDto = new UserResponseDto(user); // Constructor called once here
const plainUser = instanceToPlain(userDto); // Multiple getter calls here

Expected behavior

The getter methods should be called once per property access, minimizing redundant calls.

Actual behavior

When a single request is made, the console logs show that the constructor and getters are called multiple times:

Constructor called
First Name getter called
First Name getter called
First Name getter called
First Name getter called
First Name getter called
Last Name getter called
Last Name getter called
Last Name getter called
Last Name getter called
Last Name getter called

In the above example, Constructor called is logged once when the UserResponseDto is instantiated. However, First Name getter called and Last Name getter called are logged multiple times when instanceToPlain is called, indicating multiple unnecessary calls to the getter methods during the serialization process.

This behavior results in multiple unnecessary calls to the getter methods during the serialization process.

diffy0712 commented 2 months ago

Hello @JHyeok,

this seems to be a problem at first. I think this needs to be look at! Thank you for reporting.