Skip to content

Instantly share code, notes, and snippets.

@theangryangel
Created March 9, 2013 16:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save theangryangel/5124774 to your computer and use it in GitHub Desktop.
Save theangryangel/5124774 to your computer and use it in GitHub Desktop.
Abusing sails' policies to use existing express middleware (ie. express-form)
// 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()
);
// config/policies.js
module.exports.policies = {
// Configure the formtest action of the action controller to use the policy "forms"
'test':
{
'formtest': 'forms'
}
};
// 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;
@kojilab
Copy link

kojilab commented Mar 11, 2013

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!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment