Search code examples
typescriptentitytypeorm

Typeorm column value from sanitized other column value


I have this User class that uses typeorm. Is it possible to use the column transformer

@Entity()
class User {
  @Index(ColumnIndex.UNIQUE_EMAIL, { unique: true })
  @IsEmail()
  @Column({ type: PostgresColumn.VARCHAR })
  email: ReadOnlyColumn<string>

  @Field()
  @IsEmail()
  @Column({ type: PostgresColumn.VARCHAR })
  authoredEmail: string
}

Given a corresponding repository I'd like to be able to create like this:

user.create({
 authoredEmail: "[email protected]"
})

Somehow i'd like to "normalizeEmail" the email column Sanitizer.normalizeEmail(str, isLowercase);. Is this possible to take place in the Entity using transformer?


Solution

  • You can do anything in a transformer:

    @Column({ 
      transformer: {
        to: (value: string) => value.toLowerCase(),
        from: (value: string) => value
      }
     })
    email: string