Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize hooks, any way to get Express' user?

I'm using Sequelize and hooks (see here: https://github.com/sequelize/sequelize/pull/894). I'm trying to implement a kind of logging system, and would prefer to log on hooks instead of in my controllers. Anyone has any ideas on how I would be able to get my user from req.user into my hooks functions?

db.define('vehicle', {

    ...

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

            // Want to get my user in here.

        }
    }
});
like image 535
jValdron Avatar asked Oct 30 '13 12:10

jValdron


2 Answers

There is one simple solution that I am using in my project.

1) First when you create or update any model, pass your data in option argument like below:

model.create({},{ user: req.user}); // Or
model.update({},{ user: req.user});

2) Then, access your data inside the hook

User.addHook("afterUpdate", function(instance, options){
    console.log(' user data', options.user);
});
like image 171
Pulkit chadha Avatar answered Sep 22 '22 10:09

Pulkit chadha


Even though its an old question, here is my answer. The problem is getting the current user from your request into the hook. These steps might enable you do get that:

  1. Create a middleware with custom query functions
    req.context.findById = function(model){
      // Strip model from arguments
      Array.prototype.shift.apply(arguments);
      // Apply original function
      return model.findById.apply(model, arguments).then(function(result){
        result.context = {
          user: req.user
        }
        return result;
      });
    };
    
  2. Do your put using req.findById(model, id) instead of User.findById(id)
    app.put("/api/user/:id", app.isAuthenticated, function (req, res, next) {
       // Here is the important part, user req.context.findById(model, id) instead of model.findById(id)
       req.context.findById(User, req.params.id).then(function(item){
          // item.context.user is now req.user
          if(!user){
             return next(new Error("User with id " + id + " not found"));
          }
          user.updateAttributes(req.body).then(function(user) {
             res.json(user);
          }).catch(next);
       }).catch(next);
    });
    
  3. Use your hook, instance.context.user will be available
    User.addHook("afterUpdate", function(instance){
       if(instance.context && instance.context.user){
          console.log("A user was changed by " + instance.context.user.id);
       }
    });
    

You can find this procedure extracted into an express middleware here https://github.com/bkniffler/express-sequelize-user (I'm the creator).

like image 41
quambo Avatar answered Sep 22 '22 10:09

quambo