如何访问sails.js生命周期回调中的请求对象? [英] How to access request object in sails.js lifecycle callbacks?

查看:39
本文介绍了如何访问sails.js生命周期回调中的请求对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个模型:

module.exports = {

  attributes: {

    title: {
      type: 'string',
      required: true
    },

    content: {
      type: 'string',
      required: true
    },

    createdBy: {
      type: 'string',
      required: true
    }
  }
}

我需要将当前用户 ID 设置为模型的 createdBy 属性.我以为我可以使用 beforeValidate 生命周期回调来做到这一点,但我无法访问存储当前用户的请求对象.有没有办法访问它,或者我应该以其他方式解决这个问题?

I need to set the current user id to the model's createdBy attribute. I thought I could do that with the beforeValidate lifecycle callback, but I can't access the request object where the current user is stored. Is there a way to access it, or should I solve this somehow else?

我试过没有成功:

beforeValidate: function (values, next) {
  var req = this.req; // this is undefined
  values.createdBy = req.user.id;
  next();
}

推荐答案

由于请求超出了 ORM 的范围,我猜我的方法是错误的,我需要将 createdBy 数据添加到 req.body 中中间件.但由于不是对每个请求都这样做,我猜最好用策略来做到这一点.像这样:

Since requests are outside the scope of the ORM, I guessed my approach was wrong, and that I needed to add the createdBy data to the req.body within a middleware. But since that does not to be done for each request, I guessed it would be better to do that with a policy. Like this:

PostController: {

  '*': ['passport', 'sessionAuth'],

  create: ['passport', 'sessionAuth',
    function (req, res, next) {
      if (typeof req.body.createdBy === 'undefined') {
        req.body.createdBy = req.user.id;
      }
      next();
    }
  ]
}

这样我就不需要覆盖蓝图了.

This way I don't need to override the blueprint.

这篇关于如何访问sails.js生命周期回调中的请求对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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