typescriptsequelize.jssequelize-typescript

How to add sequelize getter to model object?


I would like to add getter to name field of the Company model object. tried several things but no luck. Unable to find a proper example as well. Sequelize version is 5.21. Would it be inside decorator or somewhere else? Trimmed code for clarity. Any help is appreciated

    export default class Company extends Model<Company> {
      @PrimaryKey
      @Default(DataType.UUIDV4)
      @Column(DataType.UUID)
      id: string;
    
      @Default(DataType.NOW)
      @Column
      created_at: Date;
    
      @Default(0)
      @Column
      deleted_at: Date;
    
      @AllowNull(false)
      @Column(DataType.STRING(25))
      name: string;
    
      @Default(true)
      @Column
      active: boolean;
    
      
    }

Solution

  • You can use VIRTUAL type of a column along with a getter and a setter:

    @Table({ modelName: 'application' })
    export class Application extends Model<Application> {
    
      @Column(DataType.VIRTUAL(DataType.STRING))
      get clientSecret(): string {
        return this.getDataValue('clientSecret')
      }
    
      set clientSecret(value: string) {
        this.setDataValue('clientSecret', value)
      }
    }
    

    See this comment in an issue