How to access request object in sails.js lifecycle callbacks?

让人想犯罪 __ 提交于 2019-12-06 02:47:31

问题


Suppose I have this model:

module.exports = {

  attributes: {

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

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

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

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?

I tried this with no success:

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

回答1:


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.




回答2:


You can do it in two ways.

First is to add that data in controller. Something like

// /api/controllers/mycontroller.js
module.exports = {
    new: function(req, res) {
        if (typeof req.user.id !== 'undefined') {
            req.body.createdBy = req.user.id;     // req.body or req.params
        }
        MyModel.create(req.body /* ... */)
    }
}

If you have a lot of data manipulation with MyModel it might be annoying. So you can add static method to your model to save it with user id. Something like:

// /api/models/myModel.js
module.exports = {
    attributes: {/* ... */},

    createFromRequest: function(req, cb) {
        // do anything you want with your request
        // for example add user id to req.body
        if (typeof req.user.id !== 'undefined') {
            req.body.createdBy = req.user.id;
        }
        MyModel.create(req.body, cb);
    }
}

And the use it in your controller

// /api/controllers/mycontroller.js
module.exports = {
    new: function(req, res) {
        MyModel.createFromRequest(req, function(err, data) {
            res.send(data);
        });
    }
}


来源:https://stackoverflow.com/questions/28370497/how-to-access-request-object-in-sails-js-lifecycle-callbacks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!