batchUpdateDoc method

Future<FeedbackResponse<WriteBatchWithReference?>> batchUpdateDoc({
  1. required Writeable writeable,
  2. required String id,
  3. WriteBatch? writeBatch,
  4. TimestampType timestampType = TimestampType.updated,
  5. String? collectionPathOverride,
})

Batch updates data based on given writeable and id.

Passing in a writeBatch will use that batch to add to it. If no batch is provided this method will create and return one.

The timestampType determines the type of automatically added _createdFieldName and/or _updatedFieldName field(s) of Timestamp. Pass in a TimestampType.none to avoid any of this automatic behaviour.

Implementation

Future<FeedbackResponse<WriteBatchWithReference?>> batchUpdateDoc({
  required Writeable writeable,
  required String id,
  WriteBatch? writeBatch,
  TimestampType timestampType = TimestampType.updated,
  String? collectionPathOverride,
}) async {
  assert(
    _isCollectionGroup == (collectionPathOverride != null),
    'Firestore does not support finding a document by id when communicating with a collection group, '
    'therefore, you must specify the collectionPathOverride containing all parent collection and document ids '
    'in order to make this method work.',
  );
  final isValidResponse = writeable.isValidResponse();
  try {
    if (isValidResponse.isSuccess) {
      _log.success('🔥 Writeable is valid!');
      _log.info('🔥 Batch updating ${collectionPathOverride ?? _collectionPath()} document with '
          'writeable: $writeable, '
          'id: $id, '
          'writeBatch: $writeBatch, '
          'timestampType: ${timestampType.name}..');
      final nullSafeWriteBatch = writeBatch ?? this.writeBatch;
      final documentReference = findDocRef(id: id);
      _log.value(documentReference.id, '🔥 Document ID');
      _log.info('🔥 Creating JSON..');
      final writeableAsJson = timestampType.add(
        writeable.toJson(),
        createdFieldName: _createdFieldName,
        updatedFieldName: _updatedFieldName,
      );
      _log.value(writeableAsJson, '🔥 JSON');
      _log.info('🔥 Updating data with writeBatch.update..');
      nullSafeWriteBatch.update(
        documentReference,
        writeableAsJson,
      );
      _log.success('🔥 Adding update to batch done! Returning WriteBatchWithReference..');
      return FeedbackResponse.successNone(
        result: WriteBatchWithReference(
          writeBatch: nullSafeWriteBatch,
          documentReference: documentReference,
        ),
      );
    }
    _log.warning('🔥 Writeable was invalid!');
    return FeedbackResponse.error(title: isValidResponse.title, message: isValidResponse.message);
  } catch (error, stackTrace) {
    _log.error(
      '🔥 Unable to batch update ${_collectionPath()} document with id: $id',
      error: error,
      stackTrace: stackTrace,
    );
    return _responseConfig.updateFailedResponse(isPlural: writeBatch != null);
  }
}