Reputation: 29
I have Database with IsBoolean
field.
IsBoolean can be 1
or 0
.
But in Javascript/Typescript I have true
or false
. It's more convenient.
I added getter to use pure boolean in Javascript.
I added setter to convert into 0/1 for Database.
Model:
const Employee = function(sequelize, DataTypes) {
return sequelize.define('employee', {
// ...Id...
IsBoolean: {
type: DataTypes.INTEGER, // Bit: 0 or 1
allowNull: false,
get() {
const value = this.getDataValue('IsBoolean');
return !!value; // from number to boolean
},
set(value) {
// from boolean to number
this.setDataValue('IsBoolean', +value);
},
},
}, {
tableName: 'employee'
});
};
Now I search instance:
Employee.findOne(
{
where: {
// getter is not being invoked
// IsBoolean: true, // doesn't work, Conversion failed
IsBoolean: 1, // works because I pass number
},
},
).then((data) => {
const result = data.get({ plain: true }); // getter works
});
// setter works
Employee.update(
{ IsBoolean: false },
{ where: {Id: 100} },
);
Getter works when I use get({ plain: true })
.
Setter works for update(..)
operation.
But getter doesn't work inside where
(and another operators).
Is there any way to fire getters inside where
?
function propagateRequired(instance) {
instance.where.IsBoolean = !!instance.where.IsBoolean;
}
hooks: {
beforeFind: propagateRequired
}
But I think it's too difficult.
Upvotes: 1
Views: 310
Reputation: 29
As a result, I use beforeFind hook
function propagateRequired(instance) {
// or add another operators (in, like)
instance.where.IsBoolean = !!instance.where.IsBoolean;
}
hooks: {
beforeFind: propagateRequired
}
For getters/setters I can use
getterMethods
and setterMethods
in the model options
or get/set (see my question) inside each field definition.
Upvotes: 1