Yomguithereal / baobab

JavaScript & TypeScript persistent and optionally immutable data tree with cursors.
MIT License
3.15k stars 117 forks source link

RFC 6902 JSON Patch support for Baobab? #441

Open dumconstantin opened 8 years ago

dumconstantin commented 8 years ago

Hi there, is there something like https://github.com/intelie/immutable-js-patch for Baobab?

Yomguithereal commented 8 years ago

Hello @dumconstantin. There is no such thing for the time being but I guess it wouldn't be too hard to create one at all. Is that something you need and consider doing in a near future?

dumconstantin commented 8 years ago

Hi @Yomguithereal, yes I'm using patches to update the Baobab state, currently my components export a stream of patches: { op: "add", // baobab operations path: ['foo', 'bar'], // baobab path value: 123 } but would like to have them use the rfc6902 standard instead.

I'd like to implement the json patch rfc for baobab, is that something I can contribute with? Do you have any thoughts on it?

Yomguithereal commented 8 years ago

I'd like to implement the json patch rfc for baobab, is that something I can contribute with?

Sure. Go ahead and create a library. If you want, I can also show you how the update method of Baobab works under the hood if it is easier to handle in your use case than the setter methods.

dumconstantin commented 8 years ago

According to RFC, if from a batch of patches one fails then no patch will be applied.

Is there any way to do a dry run of calling the update method?

Yomguithereal commented 8 years ago

There are two ways to do so. Either by providing a validator function & by setting validationBehavior to rollback (docs). Or by waiting for an update and rollbacking to last version using the event payload. But I agree this doesn't feel optimal.

Maybe it's time to add an abort or reset method to the tree along with the commit one (knowing anyway that if you set your tree to be synchronous it won't work)?

dumconstantin commented 8 years ago

Is there currently any abort / reset method I can call?

A problem I see with calling these is that if you have more updates on the tree (besides the patches) then doing an abort will remove those too.

A work around on the above would be:

  1. tree.commit()
  2. apply updates and wrap each call in a try-catch block
  3. on error do tree._transaction = [] to reset the pending changes

Although this is prone to errors, as you said, if the tree is set to update synchronous.

I think the behavior needs to be more of an atomic transaction, so along the update method maybe add a transaction method that takes a list of updates, dry-runs them and batch applying them.

dumconstantin commented 8 years ago

Hi,

You can see some progress I made here: json-patch-utils/src/applyBaobabJsPatch.js

I'll refactor this to be in tune to with the rest of the repo, but is this something that you had in mind?