Having common hooks and fields in a base class with Sequelize-Typescript

47 views Asked by At

I have several classes which have common attributes and hooks. I want to put all the code in a central class.

export class CommonFields extends Model<CommonFields> {
  @IsDate @CreatedAt @Column
  declare createdAt?: Date;

  @IsDate @UpdatedAt @Column
  declare updatedAt?: Date;

  @IsDate @DeletedAt @Column
  declare deletedAt?: Date;

  @Is(SOME_REGEX_MATCH) @Column(DataType.STRING(10))
  modifiedBy?: string;

  @BeforeCreate
  @BeforeBulkCreate
  static setCreateDate(instance: CommonFields): void {
    instance.createdAt = getUTCDateTimeNow();
    instance.updatedAt = undefined;
    instance.deletedAt = undefined;
  }

  @BeforeDestroy
  @BeforeBulkDestroy
  static setDeleteDate(instance: CommonFields): void {
    instance.deletedAt = getUTCDateTimeNow();
  }

  @BeforeUpsert
  @BeforeUpdate
  @BeforeBulkUpdate
  static setUpdateDate(instance: CommonFields): void {
    instance.updatedAt = getUTCDateTimeNow();
  }
}```

I do not want to copy and paste this code across multiple classes. Is there any way of doing this? 

The best I have come across is [this post](https://stackoverflow.com/questions/68251335/exteding-base-class-with-some-default-column-in-sequelize-with-type-support-n). However, I am not able to access the common fields or hooks with the method mentioned in the post.
0

There are 0 answers