by bastawhiz · 3y ago · 0 comments
The way _I_ would expect to do this is something like this:
const ref = db.collection('page').doc('foo');
do {
const current = await ref.get();
try {
await ref.set({ likes: current.likes + 1 }, { when: { likes: current.likes } });
} catch {
continue;
}
} while (false);
If `set()` attempts to write to the ref when the conditions in `when` are not matched exactly, the write should fail and you should have to try the operation again. In this example, the `set()` call increments the like value by one, but specifies that the write is only valid if `likes` is equal to the value that the client read. In the scenario I provided, one of the two concurrent requests would fail and retry the write (and succeed on the second go).Consider the case where a user is submitting an e-commerce order. You want to mark their order as processed and submit it for fulfillment. If you read the order to check if it's already submitted, two requests to submit it made at almost the same time (e.g., hitting the button twice) will both read that it's unfulfilled and try to each submit it.
By doing an atomic write you can be sure that at most one request submits the order.
https://cloud.google.com/firestore/docs/samples/firestore-da...
What are you using for this today?
If you're using SQLite you can use exclusive transactions to perform the read+write but I'm sure there's probably a more efficient way to go about it. You can craft an UPDATE that selects on the primary key and the condition and then use sqlite3_changes() to get back the number of records modified (and fail if it's zero), but that may not be possible with your setup.