nicklandgrebe / active-resource.js

ActiveResource.js - API resource relational mapping in JavaScript
https://active-resource.js.org
MIT License
133 stars 20 forks source link

Smart Auto-sync records to API server on change to overcome local concurrency #53

Open pelletencate opened 5 years ago

pelletencate commented 5 years ago

REST API's (and JSONAPI in particular!) are not very friendly towards concurrency, and AR.js' asynchronous implementation and direction potentially invites that to happen a lot. In our application, we save a record every time it's changed, and it's a big nuisance to keep track of record states all the time (in our case meaning it's downright impossible).

I think this management should be part of AR.js. @nicklandgrebe and I have previously talked about auto-aggregating changes throughout concurrent .save() calls so that every resource can only be updated once at a time per session, but this is very difficult to implement as it requires a centralized resource repository.

This issue is a request for an alternative solution that is both easier to build and probably easier to use for developers.

Auto Patch

Instead, we could have every change to a resource to be persisted immediately.

person = await Person.first();
person.autoPatch = true

# Initiates PATCH [name: 'John']
person.name = 'John'

# Does not initiate anything until previous PATCH is done, after which it will patch again.
person.lastName = 'Doe'
person.age = '34'

For web-based products, maybe a debouncer is handy:

person = await Person.first();
person.autoPatch(500) # Debounce 500 msec after the last change

I imagine that it incidentally can do this on a greater scale too:

Person.autoPatch().first(3) # Will enable autoPatch on all results

Immutable

Obviously, one would expect this to work flawlessly on immutable resource records too.

Supporting immutable is a bit more tricky. I think though AR.js can automatically propagate the current autoPatch behavior to subsequent records, so in order to keep track of different instances of the same resource, a bit more of a centralized approach may be necessary, but I imagine Dirty Tracking already does something similar.

kieranklaassen commented 4 years ago

Maybe this can help: https://www.npmjs.com/package/axios-observable