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?
};
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?
};
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;
},
// ...
};
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 %>