Question

I am trying to have a variable which can be accessible by all controllers in my node project. Currently in one controller I have:

        var ua = req.headers['user-agent'];
        var isMobile = "no";
        if(/mobile/i.test(ua))
            isMobile="yes";

It's pointless to copy past all of this for all my controllers and pass the isMobile variable to the view. I'd like to get the value of isMobile set once, and then pass it wherever I want from my controllers.

Is there an easy way to do this rather than have those 4 lines of code copy pasted in every controller?

Thanks

Was it helpful?

Solution

You'll want to use a Sails policy for this:

// /api/policies/isMobile.js
module.exports = function(req, res, next) {
   var ua = req.headers['user-agent'];
   req.isMobile = /mobile/i.test(ua);
   next();
}

// /config/policies.js
module.exports.policies = {
'*': 'isMobile'
};

This will run the code before every controller action, and give you access to the req.isMobile var in all of your custom controller code.

OTHER TIPS

A truly global variable isn't particularly an option as any concurrency above 1 will likely result in unexpected behavior. Being that it is something particular to the unique request itself, the req object is likely your best bet.

Assuming you have access to the req object everywhere that you would like to utilize use this flag, you can simply add a property to the req object at any point (preferably early in the request/response cycle). After this property is added, it should be available everywhere that has access to req.

  req.isMobile = /mobile/i.test(req.headers['user-agent']) ? 'yes' : 'no'; 

Or if there is a concept like middleware in express for sails

 function isMobile(req, res, next) {
   req.isMobile = /mobile/i.test(req.headers['user-agent']) ? 'yes' : 'no'; 
   next();
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top