Sequelize-typescript: Doc request: VIRTUAL field and it's getter setter

Created on 4 Sep 2020  路  1Comment  路  Source: RobinBuschmann/sequelize-typescript

I'm submitting a ...

Doc request

I know how to write a Virtual field in sequelize, but not clear for sequelize-typescript class model
All I can find are two issues:
https://github.com/RobinBuschmann/sequelize-typescript/issues/663
https://github.com/RobinBuschmann/sequelize-typescript/issues/701

But still not very clear about:

  • Do I need to put the dependent fields in type? (like DataType.VIRTUAL(DataType.STRING, ['first_name', 'last_name']))
  • How do I write a setter along with getter

So, maybe write some small examples for VIRTUAL fields in doc would help people

Most helpful comment

Hey @zhangciwu , this is an example that worked for me, for setting a "transient" field in a sequelize Model instance.

@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)
  }
}

Then, the field could be populated like so:

    const application: Application | null = await Application.findOne({where: {id}})
    if(application === null) {
        throw new Error(`application id ${id} not found`)
    }
    const clientSecret: string = await getClientSecret(application)
    application.clientSecret = clientSecret
    return application

Cheers~!

>All comments

Hey @zhangciwu , this is an example that worked for me, for setting a "transient" field in a sequelize Model instance.

@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)
  }
}

Then, the field could be populated like so:

    const application: Application | null = await Application.findOne({where: {id}})
    if(application === null) {
        throw new Error(`application id ${id} not found`)
    }
    const clientSecret: string = await getClientSecret(application)
    application.clientSecret = clientSecret
    return application

Cheers~!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

thestrayed picture thestrayed  路  5Comments

mikew picture mikew  路  4Comments

lilling picture lilling  路  4Comments

samanmohamadi picture samanmohamadi  路  5Comments

YaroslavOsetrov picture YaroslavOsetrov  路  3Comments