Transactions
Perform multiple mutations on one or more documents in an atomic manner for better performance at scale.
Transactions are useful in scenarios where you need to ensure that a series of mutations are performed as a single atomic unit of work. For example, you might want to update multiple documents as part of a single transaction to ensure that the data remains consistent across all documents.
To perform a transaction in Squid, you can use the runInTransaction
method provided by the squid
object. This method
takes a callback
function as a parameter, which will be executed within the context of a transaction.
await squid.runInTransaction(async (transactionId: string) => {
const user1 = squid.collection<User>('users').doc('user_1_id');
const user2 = squid.collection<User>('users').doc('user_2_id');
await user1.update({ name: 'Alice' }, transactionId);
await user2.update({ name: 'Bob' }, transactionId);
});
When applying changes inside a transaction, these changes will not reflect immediately, but they will reflect
optimistically once the callback
function completes.
This is in contrast to applying a mutation without a transaction, where changes are applied immediately and optimistically. Any mutation that is applied as part of a transaction will resolve immediately. In order to make sure the changes are applied on the server, you should wait for the promise returned from runInTransaction
to resolve.
When applying a transaction on multiple connectors, each connector will be updated atomically. However, it may be that one connector updated and the other one failed. There is no support for cross-connector atomic updates.