取消sails.js模型中的默认行为生命周期回调

时间:2013-08-08 03:45:41

标签: javascript node.js sails.js

假设我们创建了一个sails.js模型,有时应该在发布时保存到数据库中(像往常一样),有时候 - 不应该。我们可以在模型生命周期回调中执行此逻辑吗?

基本上,它只给我们两种方式 - 像往常一样调用next()或者调出next(错误)。还有其他选择吗?也许以某种方式可以从回调内部访问req / res对象?

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();
    }
  }
};

1 个答案:

答案 0 :(得分:4)

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