Sails.js - 如何在创建之前访问模型钩子中的会话数据 [英] sails.js - how can I acess session data in Model hook beforeCreate

查看:18
本文介绍了Sails.js - 如何在创建之前访问模型钩子中的会话数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更新模型的所有者"字段.需要从包含当前登录并正在创建模型的用户的会话中获取所有者.

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.

我想要这样的东西:

Model = {

  attributes: {

  },

  beforeCreate(values,next)
  {
    var owner_user_id  = req.session.user_id;
    values.owner = owner_user_id;
    next();
  }
}

推荐答案

您确定生命周期回调是执行此操作的正确位置吗?因为真的不是.如果明天您需要在 CLI 任务或其他无会话任务中使用您的模型怎么办?此外,随着关联 API 的出现,可能会有一种更优雅的方式来做到这一点,但仍处于模型之外.因此,现在我只是将您的引用视为一个简单的值,将其设置在操作中(您可以从中访问 req.session)并将其与其他属性一起传递给构造函数,例如:

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
}
...

这篇关于Sails.js - 如何在创建之前访问模型钩子中的会话数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆