Is there a way to have an action/function executed before each and all actions defined in a Sails controller? Similar to the beforeCreate
hooks in the models.
For example in my DataController, I have the following actions:
module.exports = {
mockdata: function(req, res) {
var criteria = {};
// collect all params
criteria = _.merge({}, req.params.all(), req.body);
//...some more login with the criteria...
},
getDataForHost: function(req, res) {
var criteria = {};
// collect all params
criteria = _.merge({}, req.params.all(), req.body);
//...some more login with the criteria...
}
};
Can I do something like the following:
module.exports = {
beforeAction: function(req, res, next) {
var criteria = {};
// collect all params
criteria = _.merge({}, req.params.all(), req.body);
// store the criteria somewhere for later use
// or perhaps pass them on to the next call
next();
},
mockdata: function(req, res) {
//...some more login with the criteria...
},
getDataForHost: function(req, res) {
//...some more login with the criteria...
}
};
Where any call to any action defined will pass through the beforeAction first?
Adding middleware To configure a new custom HTTP middleware function, add a middleware function as a new key in middleware (e.g. "foobar"), then add the name of its key ("foobar") in the middleware.
Sails uses Express for handling HTTP requests, and wraps socket.io for managing WebSockets. So if your app ever needs to get really low-level, you can access the raw Express or socket.io objects.
You can use policies here.
For example, create your custom policy as api/policies/collectParams.js
:
module.exports = function (req, res, next) {
// your code goes here
};
Than you can specify if this policy should work for all the controllers/actions, or only for specific ones in config/policies.js
:
module.exports.policies = {
// Default policy for all controllers and actions
'*': 'collectParams',
// Policy for all actions of a specific controller
'DataController': {
'*': 'collectParams'
},
// Policy for specific actions of a specific controller
'AnotherController': {
someAction: 'collectParams'
}
};
Sometimes you may need to know, what is the current controller (from your policy code). You can easily get it in your api/policies/collectParams.js
file:
console.log(req.options.model); // Model name - if you are using blueprints
console.log(req.options.controller); // Controller name
console.log(req.options.action); // Action name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With