We're working on Sails JS to build an API, which will serve only JSON responses. Can i store all request validation rules in policies. So that my main app logic (controller) would look clean.
Pros: Application logic would be clean.
Cons: Will end up creating lot of policies.
Is there any other better way to keep code clean & maintain validation rules separately?
For validations we can use libraries like express-validator.
Not sure if this is the best way to do it, but you could create a helper that does your validations. The helper could have each type of validation as its inputs, and accept arrays for each. So in your controller, you would call the helper like:
var errorObject = sails.helpers.validate.with({
alphanumeric: [inputs.userName, inputs.displayName],
isEmail: [inputs.userEmail],
...
...
})
Then your helper could take each of those inputs and loop through the arrays doing the validation checks. If a validation error occurs, return the meat of an error object. If not, return an empty object. That way in your controller you can do something like this:
if(errorObject){throw errorObject}
You would still have to include all of the exits you would want in each controller though.