batchUpdateDocuments method

Future<void> batchUpdateDocuments(
  1. Future<void> updateCallback(
    1. NimbostratusUpdateBatcher batcher
    )
)

Allows batch updating of documents using the Nimbostratus write policies on top of the Firestore WriteBatch APIs. Useful for performing optimistic cache updates that are rolled back if the batch update fails. Ex.

The first update with a WritePolicy.cacheAndServer policy will immediately update the in-memory cache and delay writing to the server until the batch is committed. The second update with the WritePolicy.serverFirst policy will defer writing to the cache until after the server response is committed. If the commit or any other API throws an exception in the batchUpdateDocuments function, then the cached changes are automatically rolled back to the values prior to when batchUpdateDocuments was called.

Implementation

// Nimbostratus.instance.batchUpdateDocuments((batch) {
//   await batch.update<Map<String, dynamic>>(
//     FirebaseFirestore.instance.collection('users').doc('alice'),
//     {
//       "name": "Alice 2",
//     },
//     writePolicy: WritePolicy.cacheAndServer,
//   );

//   await batcher.update<Map<String, dynamic>>(
//     FirebaseFirestore.instance.collection('users').doc('bob'),
//     {
//       "name": "Bob 2",
//     },
//     writePolicy: WritePolicy.serverFirst,
//   );

//   await batch.commit();
// });
/// ```
/// The first update with a [WritePolicy.cacheAndServer] policy will immediately update the in-memory cache and delay writing
/// to the server until the batch is committed.
/// The second update with the [WritePolicy.serverFirst] policy will defer writing to the cache until after the server response is
/// committed.
/// If the commit or any other API throws an exception in the [batchUpdateDocuments] function, then the cached changes are automatically rolled back to the
/// values prior to when [batchUpdateDocuments] was called.
Future<void> batchUpdateDocuments(
  Future<void> Function(NimbostratusUpdateBatcher batcher) updateCallback,
) async {
  final batcher = NimbostratusUpdateBatcher(
    firestore: firestore,
    documents: _documents,
    update: _updateDocument,
    modify: _modifyDocument,
  );

  try {
    await updateCallback(batcher);

    // Once the callback function returns, if the batch was not explicitly committed
    // in the callback, do it automatically now.
    if (!batcher.isCommitted) {
      await batcher.commit();
    }
  } catch (e) {
    batcher.rollback();
  }
}