简体   繁体   中英

Sequelize get request data in hooks?

I'm trying to store some log data for my models on create, update, delete calls. I want to store some data from the request along with some user data also in the request (using express.js).

In the hooks I have some modules for logging.

hooks: {
    afterCreate: function (order, options, done) {
        // How to get user data stored in express request.

        return app.log.set('event', [{message: 'created', data: order, userId: 1}, done]);
    }
}
...

The module just makes a record in a table. However it's the userId part I'm having trouble with. I'm using the passport module and it's stored in the request, so how can I get a user object (or any external object for that matter) into the model hooks?

I would like to avoid doing it in a controller or anywhere else as there could be some scripts or other commands that may also enter data.

I also encountered similar problems, which I myself resolved as follows:

First: I declared a Global (universal) hook:

module.exports = sequelize.addHook('beforeCreate',
  function(model, options, done) {//hook 2
    //handle what you want
    //return app.log.set('event', [{message: 'created', data: order,      userId: 1}, done]);
});

Then, Before calling model, use call hooks ( beforeCreate , beforeBulkUpdate ,...) and assigned param request

module.exports = {
  CreateUser: function(req, res) {
    User.beforeCreate(function(model, options, done) {//hook1
        model.request = req;
    });
    User.create({
            id: 1,
            username: 'thanh9999',
            password: '31231233123'
                //ex.....
        })
        .then(function(success) {
            //response success
        }, function(err) {
            //response error
        });
   }
};

order hooks called: hook declaration in model → hook 1 → hook 2`.

In addition, you also have to declare hooks for each model. See more information here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM