Skip to content

fix: Multiple Getter Calls in class-transformer #1707

Open
@JHyeok

Description

@JHyeok

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.

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