1

It is simple to get access to session property from the action of controller.

var SomeController = {
  someAction: function(req, res) {
    // no we have access to session object
    if (!req.session.hasOwnProperty('flash')) {
      req.session.flash = [];
    } 
  }
}

But I need to get access to session object from service. Example file app/services/my_servise.js:

module.exports = {
  some_method: function() {
    // here at i need to get access to session object?
    // is it possible?   
  }
}

2 Answers 2

1

See this answer for an extended discussion of why you can't access session params in model class methods; the exact same answer holds true for services. The upshot is that you must pass the request object as an argument to your service method if you want access to the session in the service code.

0

The solution very much depends on when my_service.js is called and for what purposes it is used. Here is the easiest one:

var my_service, SomeController;
my_service = require('./services/my_service.js'); // Assuming this module is in the /app directory.
SomeController = {
    'someAction': function(req, res) {
        if (!req.session.hasOwnProperty('flash')) {
            req.session.flash = [];
        }
        my_service.some_method(req);
    }
}

/app/services/my_service.js:

module.exports = {
    'some_method': function (req) {
        // use req.session
    }
};

If that's not what you're looking for, please explain my_service.js its usage a little more.

3
  • 1
    Note, you don't have to require the service, as Sails globalizes all service files automatically.
    – sgress454
    Commented May 20, 2014 at 16:12
  • @ScottGress Thanks, I hadn't seen it had to work with sails.js. I'm not familiar with that framework though. Commented May 20, 2014 at 16:30
  • I need my_service.js for saving and getting access to flash messages. Example: I send POST request to /user/login action. From data is valid. Then i redirect user from current action to /user/welcome, and i want to show some message which was generated in /user/login action. I need to use sessions fore temporary storing of lash messages. Commented May 21, 2014 at 9:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.