getter and setter sequelize simple way code example
Example 1: getter and setter sequelize simple way
method 1:
// step 1
// define getter and setter in model
const Pug = db.define('pugs', {
name: {
type: Sequelize.STRING,
get () { // this defines the 'getter'
return this.getDataValue('name') + ' the pug'
},
set (valueToBeSet) { // defines the 'setter'
// use `this.setDataValue` to actually set the value
this.setDataValue('name', valueToBeSet.toUpperCase())
// this setter will automatically set the 'name' property to be uppercased
}
}
})
//step 2
// use in code controller
// building or creating an instance will trigger the 'set' operation, causing the name to be capitalized
const createdPug = await Pug.create({name: 'cody'})
// when we 'get' createdPug.name, we get the capitalized 'CODY' + ' the pug' from our getter
console.log(createdPug.name) // CODY the pug
// this is the 'set' operation, which will capitalize the name we set
createdPug.name = 'murphy'
console.log(createdPug.name) // MURPHY the pug
Example 2: getter and setter sequelize simple way
// this for understanding of getter and setter
const someObj = {foo: 'bar'}
someObj.foo // the 'get' meta-operation
someObj.foo = 'baz' // the 'set' meta-operation
Example 3: getter and setter sequelize simple way
// method 2
//define
const User = sequelize.define('user', {
firstName: DataTypes.TEXT,
lastName: DataTypes.TEXT,
fullName: {
type: DataTypes.VIRTUAL,
get() {
return `${this.firstName} ${this.lastName}`;
},
set(value) {
throw new Error('Do not try to set the `fullName` value!');
}
}
});
//usage
const user = await User.create({ firstName: 'John', lastName: 'Doe' });
console.log(user.fullName); // 'John Doe'