使用 Sequelize 将对象传递给钩子 [英] Pass Object into hook using Sequelize

查看:34
本文介绍了使用 Sequelize 将对象传递给钩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Sequelize 用于我的节点应用程序的数据库 (SQL Server) 交互工具.我想创建一个在表有更新/交互时运行的钩子,为了这个问题,我将把这个表称为用户".我选择使用的钩子是 Sequelize 的afterBulkUpdate".

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".

我在用户"模型的定义中定义了钩子.我已经验证了当用户"更新时钩子会触发.但是,我想要做的是将已更新到afterBulkUpdate"挂钩的单个用户"传入.我的应用程序被分解为 MVC 架构,在 UserService 中实际调用 Sequelize 的.update",而钩子是在用户模型中定义的.在这两层之间是实际数据丢失的地方.

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.

TLDR:如果我将我的用户对象更新为 {"name":"fred","desc":"updated"}.当更新函数没有一行(我可以看到)调用钩子时,如何将它传递给我的 Sequelize 钩子?

TLDR: 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?

示例代码:
我的 Hook 定义:

Example Code:
My Hook definition:

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

我的 User.Update 定义:

My User.Update definition:

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

推荐答案

这些钩子接收所有与 update 相同的选项:

The hooks recieves all the same options that update does:

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

在您的钩子中,您将可以访问 options.user.这些值也应该已经在 .attributes 这里

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

另一方面,所有的 sequelize 方法都已经返回了一个 Promise,所以不需要包装它.

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

这篇关于使用 Sequelize 将对象传递给钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆