在 Sails 控制器中执行操作之前

Before actions in Sails controller

有没有办法在 Sails 控制器中定义的每个和所有操作之前执行 action/function?类似于模型中的 beforeCreate 挂钩。

例如,在我的 DataController 中,我有以下操作:

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...
  }
};

我可以做类似下面的事情吗:

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...
  }
};

对定义的任何操作的任何调用都将首先通过 beforeAction?

是的,您可以将策略用作 beforeAction。

文档显示它用于身份验证,但它基本上可以用于您的目的。您只需将之前的操作放在政策中。

http://sailsjs.org/#!/documentation/concepts/Policies

您可以在此处使用策略。

例如,将自定义策略创建为 api/policies/collectParams.js:

module.exports = function (req, res, next) {
    // your code goes here
};

您可以指定此政策是适用于所有 controllers/actions,还是仅适用于 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'
    }
};

有时您可能需要知道当前控制器是什么(来自您的策略代码)。您可以轻松地在 api/policies/collectParams.js 文件中获取它:

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