How to add a custom DataType in Sequelize ORM

余生颓废 提交于 2019-12-05 23:48:26

https://github.com/sequelize/sequelize/blob/master/lib/data-types.js holds the sequelize data types.

Specifically, https://github.com/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.com/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.

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.com/sequelize/sequelize/issues/8533

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!