3

Let's say we create a sails.js model, which sometimes should be saved into DB when posted (as usual), and sometimes – should not. Can we perform this logic in a model lifecycle callback?

Basically, it gives us just two ways – proceed as usual calling next() or raise an error calling next(err). Are there any other options? Maybe it's somehow possible to get access to req/res objects from inside the callback?

module.exports = {

  attributes: {
  },

  // Lifecycle Callbacks
  beforeCreate: function(values, next) {
    //analyze values

    if (someCondition) {
      //now we realize that we don't want the model to be created
      //we need perform some other stuff and respond with some custom answer
      //how do we do that?
    } else {
      next();
    }
  }
};
4

1 回答 1

4

这就是控制器的工作,你不想将 req/res 对象引入模型。检查是否应该创建记录属于控制器方法。在调用 Model.create() 时,您应该已经知道是否要创建它。如果您想使用蓝图或减少代码重复,您可以使用可以附加到路由的策略(中间件)并在调用 Model.create() 之前进行检查。

于 2013-08-11T22:00:30.597 回答