OrwellHindenberg OrwellHindenberg - 1 year ago 166
Node.js Question

Pass Object into hook using Sequelize

I am using Sequelize for my node application's database (SQL Server) interaction tool. I want to create a hook that runs any time there is an update/interation to a table, I will call this table "User" for the sake of this question. The hook I have chosen to use is Sequelize's "afterBulkUpdate".

I defined the hook within the definition of my "User" model. I have verified that the hook fires when the "User" is updated. However, what I want to do is to pass in the individual "User" that has been updated to the "afterBulkUpdate" hook. My application is broken up into the MVC architecture with the actual call to Sequelize's ".update" inside a UserService while the hook is defined within the User Model. In between those two layers is where the actual data gets lost.

If I update my User object to {"name":"fred","desc":"updated"}. How do I pass this to my Sequelize hook when the update function doesn't have a line (that I can see) calling the hook?

Example Code:

My Hook definition:

afterBulkUpdate: (user, options) ->
console.log "Do something with the actual data here"

My User.Update definition:

update: (user) ->
new Promise (resolve, reject) ->
name: user.name
.then (res) ->
resolve res
.catch (err) ->
reject err

Answer Source

The hooks recieves all the same options that update does:

User.update(user, { where ..., user: user })

In your hook, you will then have access to options.user. The values should also already be available in .attributes here

On another note, all sequelize methods already return a promise, so there is no need to wrap it.