node.jssails.jssails-postgresql

Sails JS: Pass parameter to toJSON


The sailsjs model attribute method toJSON is very handy for processing model attributes before sending back to client. However, this method does not take any parameters and I cannot pass additional information to the method that can be used for processing attributes.

In my particular case, I need to check if I should send an attribute by comparing logged in user id (req.user.id). E.g.

toJSON: function () {
  var obj = this.toObject();
  var result = {};
  if (req.user.id === 123) {  // How can I access req from inside toJSON?
    // do something here ...
  }
}

I could not find a way to access the req parameter from inside toJSON. Any suggestions?


Solution

  • Sails does purposely not expose the req attribute as a global so there is no way to access it from within toJSON: How to access session variables outside controller

    Depending on the functionality you are trying to achieve you might be able to use policies instead: How to access request object in sails js lifecycle callbacks

    In a similar case, I found myself using a workaround instead. You can add the id of the logged in user in your controller to the model:

    YourModel.findOne().exec(function (err, yourModelObject) {
    
        yourModelObject.loggedInUserId = req.user.id;
        res.send(yourModelObject);
    
    });
    

    It is then accessible in your toJSON method and you could use it like this:

    toJSON: function () {
        var obj = this.toObject();
        var result = {};
    
        if (obj.loggedInUserId === 123) {  
         // do something here ...
        }
    
        delete obj.loggedInUserId;
    
        return obj;
    }
    

    It is a little bit of a hack, but it worked for me. Be careful that a user can't somehow set the same value on the model (for example by using schema: true in your model) in question, to prevent security holes in your code.