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

查看:69
本文介绍了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天全站免登陆