Sequelize: defaultScope as function

Created on 17 Jun 2016  路  3Comments  路  Source: sequelize/sequelize

PR #5772 seems as an attemp made by someone else, but it should call the defaultScope function each time, not at initialization only.
Well the issue for me comes when I want to make a defaultScope from other scopes I need a function like this:

//Currency.js
{ 
 //...
defaultScope: function() {
  return {
    include: this.scopes.includeExchanges().include.concat( 
             this.scopes.includeSystemDefaults().include )
  }
},
scopes: {
  includeExchanges: function(where) {
    return {
      include: [
        {
          as: 'exchanges',
          model: models.CurrencyExchange,
          required: false,
          where: where||{}
        }
      ]
    }
  },
  includeSystemDefaults: function() {
    return {
      include: [
        {
          as: 'systemDefaults',
          model: models.SysCurrency,
          required: true
        }
      ]
    }
  }
},

Where by the way I need to manually merge the includes because the scope's merging mecanism does not support that case.

Most helpful comment

Ok, I did the following, use functions as defaultScope and after defining all models I run it's associations and replace each defaultScope's functions with the result of calling it.

models.forEach(model => {
  if(typeof model.options.defaultScope == 'function') 
    model.addScope('defaultScope', model.options.defaultScope(), { override: true })
})

All 3 comments

Scopes as objects are useless for includes where you need to have your models already defined

You can use addScope to add scopes that depend on other models being defined. I really don't think the added complexity of allowing defaultScope to be a function is worth the trouble

Ok, I did the following, use functions as defaultScope and after defining all models I run it's associations and replace each defaultScope's functions with the result of calling it.

models.forEach(model => {
  if(typeof model.options.defaultScope == 'function') 
    model.addScope('defaultScope', model.options.defaultScope(), { override: true })
})
Was this page helpful?
0 / 5 - 0 ratings