【问题标题】:Before actions in Sails controllerSails 控制器中的操作之前
【发布时间】:2015-06-21 21:35:33
【问题描述】:

有没有办法在 Sails 控制器中定义的每个和所有操作之前执行一个操作/功能?类似于模型中的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?

【问题讨论】:

  • 改用策略,它会让你的代码看起来更清晰

标签: orm sails.js waterline


【解决方案1】:

您可以在此处使用政策。

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

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

您可以指定此策略是适用于所有控制器/操作,还是仅适用于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

【讨论】:

  • 太棒了!谢谢。对此还有一个补充。可以按定义的顺序链接策略。根据文档而不是添加特定策略,您可以添加一个数组,例如到编辑方法edit: ['isAdmin', 'isLoggedIn'] 如果明确列出了某个操作,则其策略列表将覆盖默认列表。
【解决方案2】:

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

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

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

【讨论】:

  • 感谢您的链接。如@Leestex 回答中所述,这看起来像是解决方案。
猜你喜欢
  • 1970-01-01
  • 2011-11-22
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多