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?   
  }
}
YarikKotsur
  • 136
  • 1
  • 4

2 Answers2

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.

Community
  • 1
  • 1
sgress454
  • 24,870
  • 4
  • 74
  • 92
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.

dot slash hack
  • 558
  • 1
  • 5
  • 13
  • 1
    Note, you don't have to `require` the service, as Sails globalizes all service files automatically. – sgress454 May 20 '14 at 16:12
  • @ScottGress Thanks, I hadn't seen it had to work with sails.js. I'm not familiar with that framework though. – dot slash hack May 20 '14 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. – YarikKotsur May 21 '14 at 09:27