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

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 createdBy attribute. I thought I could do this with the beforeValidate lifecycle callback, but I cannot access the request object that the current user is stored in. Is there a way to access it, or should I solve it somehow differently?

I tried this without success:

 beforeValidate: function (values, next) { var req = this.req; // this is undefined values.createdBy = req.user.id; next(); } 
+5
source share
3 answers

Since the queries are outside the scope of ORM, I guessed that my approach was wrong and that I needed to add the createdBy data to req.body as part of the middleware. But since this is not done for every request, I suggested that it would be better to do this 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 do not need to redefine the project.

+8
source

You can do this in two ways.

First you need to add this data to the controller. Sort of

 // /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 using MyModel , this can be annoying. This way you can add a static method to your model to save it with a user id. Sort of:

 // /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 using it in your controller

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

Sails purposefully does not provide req and res objects for lifecycle callbacks, which means that you should not do what you are trying to do.

If you are trying to set a user ID, you can add this id to the req.query object inside the sails policy; then if you just use a standard REST endpoint, the identifier will be automatically added to the model. My sails-auth module does something similar.

-2
source

Source: https://habr.com/ru/post/1212823/


All Articles