Plastic Rabbit
Plastic Rabbit

Reputation: 2999

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

Upvotes: 1

Views: 6435

Answers (1)

sdepold
sdepold

Reputation: 6241

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'
  })
})

Upvotes: 7

Related Questions