@deco.Virtual
The @deco.Virtual
decorator enables setting of fields as if they corresponded to columns in the model's table so they can be passed to new, create, and update.
For example, in the first example, below, one could call await bodyMeasurement.update({ lbs 180.1 })
, and 180.1
will be passed into the lbs
setter, which then translates lbs to grams to be stored in the grams
column in the metrics table.
And in the second example, below, one could call await user.update({ password })
, and, in the BeforeSave lifecycle hook, the password would be hashed into hashedPassword
. (This is just an example to illustrate using the Virtual decorator on a simple field; it might be better design to use the getter/setter pattern for password, with the getter simply returning undefined
.)
class BodyMeasurement extends ApplicationModel {
@deco.Virtual()
public get lbs() {
const self: User = this
return gramsToLbs(self.getAttribute('grams') ?? 0)
}
public set lbs(lbs: number) {
const self: User = this
self.setAttribute('grams', lbsToGrams(lbs))
}
@deco.Virtual()
public get kilograms() {
const self: User = this
return gramsToKilograms(self.getAttribute('grams') ?? 0)
}
public set kilograms(kg: number) {
const self: User = this
self.setAttribute('grams', kilogramsToGrams(kg))
}
}
class User extends ApplicationModel {
@deco.Virtual()
public password: string
@deco.BeforeSave()
public hasPassword() {
this.setAttribute(
'hashedPassword',
preferredHashingAlgorithm(this.password)
)
}
}