Created
March 9, 2013 16:45
-
-
Save theangryangel/5124774 to your computer and use it in GitHub Desktop.
Abusing sails' policies to use existing express middleware (ie. express-form)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// api/policies/form.js | |
// npm install express-form@@0.7.x in the root of your project - sails currently uses express 2 | |
var form = require('express-form'), | |
filter = form.filter, | |
validate = form.validate; | |
// create our policy, which happens to be an express-form | |
module.exports = form( // Form filter and validation middleware | |
filter("username").trim(), | |
validate("username").required().is(/^[a-z]+$/), | |
filter("password").trim(), | |
validate("password").required().is(/^[0-9]+$/), | |
filter("email").trim(), | |
validate("email").isEmail() | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// config/policies.js | |
module.exports.policies = { | |
// Configure the formtest action of the action controller to use the policy "forms" | |
'test': | |
{ | |
'formtest': 'forms' | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// api/controllers/TestController.js | |
var TestController = { | |
// since the policy will have run, we can now use req.form as "normal" | |
formtest: function(req, res) | |
{ | |
if (!req.form.isValid) | |
{ | |
// Handle errors | |
console.log(req.form.errors); | |
} | |
else | |
{ | |
// Or, use filtered form data from the form object: | |
console.log("Username:", req.form.username); | |
console.log("Password:", req.form.password); | |
console.log("Email:", req.form.email); | |
} | |
// render the view | |
res.view(); | |
} | |
}; | |
module.exports = TestController; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
IT's working nicely. I actually like this approach. In a way it's acting as a filter and could be very handy to validate an API payload. Thanks a lot!!