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.
}
}
});
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);
});
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:
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; }); };
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); });
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With