Search code examples
parametersaclsails.jscontrollerspolicies

Passing Parameters to sails.js policies


Sails.js (0.9v) controllers have policies defined as:

RabbitController: {

    '*': false, 

    nurture    : 'isRabbitMother',

    feed : ['isNiceToAnimals', 'hasRabbitFood']
}

is there a way to pass params to these acls eg:

RabbitController: {

    '*': false, 

    nurture    : 'isRabbitMother(myparam)',

    feed : ['isNiceToAnimals(myparam1, myparam2)', 'hasRabbitFood(anotherParam)']
}

This may lead to multiple use of these functions for different params. Thanks Arif


Solution

  • The policies are middleware functions with the signature:

        function myPolicy (req, res, next)
    

    There's no way to specify additional parameters for these functions. However, you could create wrapper functions to create the policies dynamically:

        function policyMaker (myArg) {
          return function (req, res, next) {
            if (req.params('someParam') == myArg) {
              return next();
            } else {
              return res.forbidden();
            }
          }
        }
    
        module.exports = {
    
          RabbitController: {
            // create a policy for the nurture action
            nurture: policyMaker('foo'),
            // use the policy at 
            // /api/policies/someOtherPolicy.js for the feed action
            feed: 'someOtherPolicy'
          }
    
        }
    

    In practice you'd want to separate this code into another file and require it, but this should get you started.