sails.js - how can I acess session data in Model hook beforeCreate

后端 未结 1 981
花落未央
花落未央 2021-01-05 12:33

I want to update a field \'owner\' of a Model. The owner needs to be fetched from the session which contains the user who is currently logged in and is creating the Model.

相关标签:
1条回答
  • 2021-01-05 13:13

    Are you sure a lifecycle callback is the right place to do it? Because it's really not. What if tomorrow you'll need to use your model in a CLI task or something else sessionless? Besides, with the associations API coming, there will be, probably, a more elegant way to do it, but still outside of the model. So, for now I would just treat your reference as a simple value, set it in the action (from where you can access req.session) and pass to the constructor along with other properties, something like:

    ...
    // Controller code
    module.exports = {
      index: function(req, res) {
        // Whatever gets you the values...
    
        values.owner = req.session.user_id;
        Model.create(values, function(err, model) {...});
      },
      // Other actions
    }
    ...
    
    0 讨论(0)
提交回复
热议问题