JS-Data v3.0 stop execution in lifecycle hook

50 views Asked by At

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.

1

There are 1 answers

0
Raymundus On

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,
  },
})