简体   繁体   中英

How to extend Sequelize model

Is there a way to extend (maybe inherit) model to add hooks and fields after model was defined?

So something like this:

User = sequelize.define("user", {
   name: sequelize.String
});

makeStateful(User); // adds state,updated,added fields and some hooks

this is not possible at the moment. But you could easily make it work the other way around: Define your mixin before and use that when you define the model:

var Sequelize = require('sequelize')
  , sequelize = new Sequelize('sequelize_test', 'root')

var mixin = {
  attributes: {
    state: Sequelize.STRING,
    added_at: Sequelize.DATE
  },
  options: {
    hooks: {
      beforeValidate: function(instance, cb) {
        console.log('Validating!!!')
        cb()
      }
    }
  }
}

var User = sequelize.define(
  'Model'
, Sequelize.Utils._.extend({
    username: Sequelize.STRING
  }, mixin.attributes)
, Sequelize.Utils._.extend({
    instanceMethods: {
      foo: function() {
        return this.username
      }
    }
  }, mixin.options)
)

User.sync({ force: true }).success(function() {
  User.create({ username: 'foo' }).success(function(u) {
    console.log(u.foo()) // 'foo'
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM