【问题标题】:Cancelling default behaviour in sails.js model Lifecycle callback取消sails.js模型生命周期回调中的默认行为
【发布时间】:2013-08-08 03:45:40
【问题描述】:

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

基本上,它只给了我们两种方法——像往常一样调用 next() 或引发错误调用 next(err)。还有其他选择吗?也许有可能从回调内部访问 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();
    }
  }
};

【问题讨论】:

    标签: javascript node.js sails.js


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      相关资源
      最近更新 更多