【问题标题】:JS-Data v3.0 stop execution in lifecycle hookJS-Data v3.0 在生命周期钩子中停止执行
【发布时间】:2019-03-09 21:36:07
【问题描述】:

我正在使用 js-data v3.0,如果在保存时更改了记录,我正在尝试防止在 update 上从我的 API 接收到的记录进行存储注入。

在 js-data v2.9 中,可以通过调用带有错误作为参数的回调来中止生命周期 (docs)

现在在 v3.0 中,我正在使用 mapper#afterUpdate() 生命周期挂钩 (docs),但我不知道如何中止生命周期。

【问题讨论】:

    标签: jsdata lifecycle-hook


    【解决方案1】:

    显然返回 null 可以防止存储注入。

    防止update回调覆盖save()期间对记录所做的更改的完整代码:

    function beforeUpdate(id, props, opts) {
      const currentStoreItem = this.datastore.get(opts.name, id)
      opts.tlChangesBeforeUpdate = JSON.stringify(currentStoreItem.changes())
      return this.constructor.prototype.beforeUpdate.call(this, id, props, opts)
    }
    
    function afterUpdate(id, props, opts, result) {
      const currentStoreItem = this.datastore.get(opts.name, id)
      const currentChanges = JSON.stringify(currentStoreItem && currentStoreItem.changes())
      if (currentChanges != opts.tlChangesBeforeUpdate) return null // This prevents store injecton
      return this.constructor.prototype.afterUpdate.call(this, id, props, opts, result)
    }
    
    const ds = new DataStore({
      mapperDefaults: {
        beforeUpdate: beforeUpdate,
        afterUpdate: afterUpdate,
      },
    })
    

    【讨论】:

      猜你喜欢
      • 2018-04-23
      • 2022-01-22
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多