I want to define a custom data type in Sequelize
by inheriting all default behaviours of existing DataType.Integer
. The base idea here is to define a new type and override valueOf
and toString
methods.
The Sequelize docs doesn't contain any information related to this topic. It would be really nice if someone can help me on this.
I want to define a custom data type in Sequelize
by inheriting all default behaviours of existing DataType.Integer
. The base idea here is to define a new type and override valueOf
and toString
methods.
The Sequelize docs doesn't contain any information related to this topic. It would be really nice if someone can help me on this.
Share Improve this question asked Jan 4, 2016 at 2:50 PIKPPIKP 8432 gold badges17 silver badges26 bronze badges 1- Sequelize v5 documentation – Avraham Commented Jun 10, 2021 at 11:53
3 Answers
Reset to default 2https://github./sequelize/sequelize/blob/master/lib/data-types.js holds the sequelize data types.
Specifically, https://github./sequelize/sequelize/blob/master/lib/data-types.js#L251-L273 shows how DataTypes.INTEGER inherits from DataTypes.NUMBER using NUMBER.inherits(fn)
.
Those inherit from ABSTRACT. You could override the toString()
method for your inherited data type like as seen at https://github./sequelize/sequelize/blob/master/lib/data-types.js#L62-L64.
Disclaimer: with it not being publicly documented, I am not sure how stable the APIs are and would be cautious due to possible future changes.
In v6, Sequelize provides a guide, with code examples, on how to do this. It is similar to the solutions already provided, but I thought it should be added here for pleteness.
https://sequelize/docs/v6/other-topics/extending-data-types/
To extend DataTypes in Sequelize:
class DataTypes_IP extends DataTypes.ABSTRACT {
constructor () {
super()
this.key = 'IP'
}
toSql() {
return 'VARBINARY(16)'
}
// Todo
validate (value) {
// const Validator = require('./utils/validator-extras').validator
// if (!Validator.isDate(String(value))) {
// throw new sequelizeErrors.ValidationError(util.format('%j is not a valid date', value))
// }
return true
}
_sanitize (value) {
return new IP(value)
}
_isChanged (value, originalValue) {
if (value === originalValue) return false
if (
value instanceof IP &&
originalValue instanceof IP &&
value.toBuffer().equals(originalValue.toBuffer())
) {
return false
}
return true
}
_stringify (ip) {
return ip.toBuffer()
}
}
And extends the DataTypes
DataTypes.IP = DataTypes_IP
You can check the relevant issue in github. https://github./sequelize/sequelize/issues/8533