josephdotca
josephdotca

Reputation: 378

Express js + Sequelize and hook

I am developping an application where I need to make extra validation on creating an object.

I tried using hooks and the beforeValidate function, but it's not working. I'm trying to fail the validation if the value submitted is greater than the value from the db (computed value based on custom query).

Transaction.beforeValidate(function(transaction, options) {

    sequelize.query(
      'SELECT SUM(IF(type = "buy", number_of_shares, number_of_shares * -1)) as remaining FROM transactions WHERE account_id = $account_id',
      { 
        bind: { 
          account_id: req.body.account_id 
        }, 
        type: sequelize.QueryTypes.SELECT 
      }
    ).then(result => {
      if (req.body.type == "sell" && result.remaining < req.body.number_of_shares) {
        throw error('Number of remaining shares is less than what you are trying to sell.') // psudeo code
      }
    }).then(result => {
      return sequelize.Promise.resolve(user);
    })
  })

Upvotes: 0

Views: 209

Answers (1)

Gunar Gessner
Gunar Gessner

Reputation: 2641

You're missing a return before sequelize.query(.

return sequelize.query(

Upvotes: 1

Related Questions