In sails.js, how to access session variables outside controller?

流过昼夜 提交于 2019-12-12 15:01:28

问题


In controller, it's easy. Accessing a session variables is straightforward:

req.session.x = 1

However, how do I access that outside controller? Like in service?

module.exports.test = function() {
    // No req.session here?
};

回答1:


The session object in Sails isn't provided as a global; it's a property of the Request object. For server-side code that doesn't included the request as part of the scope (like services and models), you'll need to pass the request or the session along as an argument to your function:

modules.exports.test = function(session) {
   ...
}

and call it from a controller with MyService.test(req.session).

Note that for views, req is passed down by default with the view locals, so you can do (in EJS) things like:

<%= req.session.myVar %>



回答2:


You can create a main controller that will register req and res in all of your services for each route controller called.

Here is the code of my main controller:

module.exports = function MainController() {

  var _this = this;

  function _execRouteMethod(req, res) {
    // Add here your services or whatever with a registration
    // of req and/or res variables
    ActiveUserService.registerRequest(req);
  }

  // Abstract function for calling registers before the original method
  function _abstractRouteMethod(functionName) {
    var funcSuper = _this[functionName];
    _this[functionName] = function(req, res) {
      _execRouteMethod(req, res);
      funcSuper(req, res);
    }
  }

  // Loop for all method that have req and res arguments
  for(var functionName in this) {
    if(typeof this[functionName] == 'function') {
      var args = /function[^\(]*\(([^\)]*)\)/.exec(
        this[functionName].toString()
      );
      if(args && args.length > 1) {

        args = args[1].split(',').map(function(arg) {
          return arg.trim()
        });

        if(args.length == 2 && args[0] == 'req' && args[1] == 'res') {
          _abstractRouteMethod(functionName);
        }
      }
    }
  }

};

Now you can call it in any of your controllers :

var MainController = require('./MainController');
MainController.call(MyController);

Your services can use the req and res registered. For exemple, I use it in my ActiveUserService like this:

var _request = null;

var ActiveUserService = {

  registerRequest: function(req) {
    _request = req;
  },

  isConnected: function () {
    return _request && _request.session.user ? true : false;
  },

  // ...

};


来源:https://stackoverflow.com/questions/22833573/in-sails-js-how-to-access-session-variables-outside-controller

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