Sequelize钩子,以任何方式获得Express'用户?

jVa*_*ron 5 node.js express sequelize.js

我正在使用Sequelize和钩子(见这里:https://github.com/sequelize/sequelize/pull/894).我正在尝试实现一种日志系统,并且更愿意登录钩子而不是我的控制器.任何人都有任何关于如何将我的用户从req.user带入我的钩子函数的想法?

db.define('vehicle', {

    ...

}, {
    hooks: {
        beforeUpdate: function(values, cb){

            // Want to get my user in here.

        }
    }
});
Run Code Online (Sandbox Code Playgroud)

Pul*_*dha 5

我在我的项目中使用了一种简单的解决方案。

1)首先,当您创建或更新任何模型时,将您的数据传递到选项参数中,如下所示:

model.create({},{ user: req.user}); // Or
model.update({},{ user: req.user});
Run Code Online (Sandbox Code Playgroud)

2)然后,访问钩子内的数据

User.addHook("afterUpdate", function(instance, options){
    console.log(' user data', options.user);
});
Run Code Online (Sandbox Code Playgroud)


qua*_*mbo 4

尽管这是一个老问题,但这是我的答案。问题是将当前用户从您的请求中获取到挂钩中。这些步骤可能会让您明白:

  1. 创建具有自定义查询功能的中间件
    req.context.findById = 函数(模型){
      // 从参数中剥离模型
      Array.prototype.shift.apply(参数);
      // 应用原始函数
      返回 model.findById.apply(模型, 参数).then(函数(结果){
        结果.上下文 = {
          用户:req.user
        }
        返回结果;
      });
    };
    
  2. 做你的 put 使用req.findById(model, id)而不是User.findById(id)
    app.put("/api/user/:id", app.isAuthenticated, function (req, res, next) {
       // 这里是重要的部分,用户 req.context.findById(model, id) 而不是 model.findById(id)
       req.context.findById(用户, req.params.id).then(函数(项目){
          // item.context.user 现在是 req.user
          如果(!用户){
             return next(new Error("未找到 id 为 " + id + " 的用户"));
          }
          user.updateAttributes(req.body).then(函数(用户) {
             res.json(用户);
          }).catch(下一个);
       }).catch(下一个);
    });
    
  3. 使用你的钩子,instance.context.user将可用
    User.addHook("更新后", 函数(实例){
       if(instance.context && instance.context.user){
          console.log("用户被更改为 " + instance.context.user.id);
       }
    });
    

您可以在此处找到提取到快速中间件中的此过程https://github.com/bkniffler/express-sequelize-user(我是创建者)。