Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Before actions in Sails controller

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?

like image 576
tuvokki Avatar asked Apr 15 '15 18:04

tuvokki


People also ask

How do I use middleware in sails JS?

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.

Does sails use Express?

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.


1 Answers

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
like image 86
Nazar Avatar answered Sep 28 '22 19:09

Nazar