Search code examples
typescripttypeorm

Prevent empty string in Entity column in TypeOrm


I want to prevent the insertion of an empty string for a string column.

Aside: Yes I can do the constraint in the DB, and I will do that.

I would like it so if an empty string is assigned to that property, typeorm will automatically null it.

For example, I imagine something like:

@Entity()
class Foo {
  @Column()
  @NoEmptyString()
  bar: string;
}

and then if someone were to:

const foo = new Foo();
foo.bar = '';
repository.save(foo);

then foo would be inserted with NULL as the value of bar.

TypeORM also has validations but they actually seem to all come from class-validator and need to be called manually.


Solution

  • @Entity()
    class Foo {
      @Column()
      @NoEmptyString()
      bar: string;
    
      @BeforeInsert()
      @BeforeUpdate()
      replaceEmptyStringAsNull() {
        if (this.bar === '') {
          this.bar = null;
        }
      }
    }