DEV Community

Cover image for Fixing Getter/Setter Issues in TypeORM Entity(The Clean Way with transformer)
Sarwar Hossain
Sarwar Hossain

Posted on

Fixing Getter/Setter Issues in TypeORM Entity(The Clean Way with transformer)

πŸ‘€ Overview:

Have you tried to implement getter/setter in your entity of TypeORM?
But Not found exact though use of AI.

🐞 The Problem :

  1. I try to map a private _userType to a public userType getter/setter.
  2. TypeORM still reads/writes the raw _userType field without calling get/set.
  3. The conversion code inside get userType() / set userType() is never applied

❌ Have you tried like below ?
And getting the
"Error: Missing column value in entity for: user_type
"

❌

@Entity()
export class User {
  @Column({ name: 'user_type', type: 'int' })
  private _userType: number;

  // These will NOT be used by TypeORM:
  get userType(): string {
    return this._userType === 1 ? 'ADMIN' : 'USER';
  }
  set userType(val: string) {
    this._userType = val === 'ADMIN' ? 1 : 0;
  }
}

Enter fullscreen mode Exit fullscreen mode

βœ… The Fix: Use transformer

Works perfectly β€” no more errors, and clean transformations. Instead of getters/setters, use TypeORM’s built-in transformer option on the column

@Entity()
export class User {
  @Column({
    name: 'user_type',
    type: 'int',
    transformer: {
     to(role: string): number {
       return role === 'ADMIN' ? 1 : 0;
     }
     from(value: number): string {
       return value === 1 ? 'ADMIN' : 'USER';
     }
   };
  })
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)