tuv*_*kki 5 orm sails.js waterline
有没有办法在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...
}
};
Run Code Online (Sandbox Code Playgroud)
我可以做以下事情:
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...
}
};
Run Code Online (Sandbox Code Playgroud)
如果对定义的任何操作的任何调用将首先通过beforeAction?
您可以在此处使用策略。
例如,将自定义策略创建为api/policies/collectParams.js
:
module.exports = function (req, res, next) {
// your code goes here
};
Run Code Online (Sandbox Code Playgroud)
您可以指定此策略是否适用于所有控制器/操作,或者仅适用于以下中的特定控制器/操作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'
}
};
Run Code Online (Sandbox Code Playgroud)
有时您可能需要知道当前控制器是什么(来自您的策略代码)。您可以轻松地将其添加到您的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
Run Code Online (Sandbox Code Playgroud)