Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add express middleware for param validations

In a sails.js application is there a simple way of including express-middleware?

For instance extending the request object with express-validator.

like image 720
jqualls Avatar asked Aug 13 '13 17:08

jqualls


2 Answers

Adding express-middleware in a sails application is simple.

create a new policy.

policies
  |_
    middleware.js / .coffee

Add Express MiddlewareYOUR_MIDDLE_WARE_FILE_NAME.js

Inside your middleware file we create the standard export for node.js

module.exports = require('middle-ware')(OPTIONS_GO_HERE) // See middleware docs for configuration settings.

Then once you have created the middleware you can apply it to all requests or a single controller by following the Sails.js convension.

Entire Applicationpolicies.js

module.exports.policies = {
   '*':['middleware'] // node same name as file without extention
}

Single Controller Action policies.js

module.exports.policies = {
   RabbitController:{
      feed:['middleware']
   }
}
like image 116
jqualls Avatar answered Nov 09 '22 12:11

jqualls


First of all, @SkyTecLabs' answer is the proper way to do this. But I wanted to add that, in some cases, you may need to control your static files (images, client-side javascript, css, etc) as well (I just had to deal with this recently). In this case, you can apply middleware generically to every route.

As of Sails.js v0.9.3, you can do:

// Put this in `config/express.js`
module.exports.express = {
  customMiddleware: function (app) {
    app.use(require('../node_modules/sails/node_modules/express').basicAuth('balderdash', 'wickywocky'));
  }
};

More here: https://gist.github.com/mikermcneil/6255295

In the case where you want middleware to run before one or more of your controllers or actions, you're definitely better served using the policy approach though!

like image 38
mikermcneil Avatar answered Nov 09 '22 14:11

mikermcneil