1

I am using js-data v3.0 and i am trying to prevent store-injection of the record received from my API upon update if the record was changed while saving.

In js-data v2.9 one could abort the lifecycle by calling a callback with an error as argument (docs)

Now in v3.0 I'm using the mapper#afterUpdate() lifecycle hook (docs), but I don't know how to abort the lifecycle.

Raymundus
  • 2,173
  • 1
  • 20
  • 35

1 Answers1

1

Apparently returning null prevents store-injection.

Full code to prevent the update callback from overwriting changes made on the record during the 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,
  },
})
Raymundus
  • 2,173
  • 1
  • 20
  • 35