batchCreateDoc method

Future<FeedbackResponse<WriteBatchWithReference?>> batchCreateDoc({
  1. required Writeable writeable,
  2. String? id,
  3. WriteBatch? writeBatch,
  4. TimestampType createTimeStampType = TimestampType.createdAndUpdated,
  5. TimestampType updateTimeStampType = TimestampType.updated,
  6. bool merge = false,
  7. List<FieldPath>? mergeFields,
  8. String? collectionPathOverride,
})

Batch creates/writes data based on given writeable.

Passing in an id will give your document that 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 createTimeStampType determines the type of automatically added _createdFieldName and/or _updatedFieldName field(s) of Timestamp when merge is false. Pass in a TimestampType.none to avoid any of this automatic behaviour.

The updateTimeStampType determines the type of automatically added _createdFieldName and/or _updatedFieldName field(s) of Timestamp when merge is true or mergeFields != null. Pass in a TimestampType.none to avoid any of this automatic behaviour.

When merge is true this method will attempt an upsert if the document exists. If the document does not exist it will default to a regular create.

If addIdAsField is true it will automatically add the ID (given as id or generated) as a field to your document. The field name will be what's specified in _idFieldName.

The mergeFields determine which fields to upsert, leave blank to upsert the entire object.

Implementation

Future<FeedbackResponse<WriteBatchWithReference?>> batchCreateDoc({
  required Writeable writeable,
  String? id,
  WriteBatch? writeBatch,
  TimestampType createTimeStampType = TimestampType.createdAndUpdated,
  TimestampType updateTimeStampType = TimestampType.updated,
  bool merge = false,
  List<FieldPath>? mergeFields,
  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.',
  );
  try {
    final isValidResponse = writeable.isValidResponse();
    if (isValidResponse.isSuccess) {
      _log.success('🔥 Writeable is valid!');
      _log.info(
        '🔥 '
        'Batch creating ${collectionPathOverride ?? _collectionPath()} document with '
        'writeable: $writeable, '
        'id: $id, '
        'writeBatch: $writeBatch, '
        'createTimeStampType: ${createTimeStampType.name}, '
        'updateTimeStampType: ${updateTimeStampType.name}, '
        'merge: $merge, '
        'mergeFields: $mergeFields..',
      );
      final nullSafeWriteBatch = writeBatch ?? this.writeBatch;
      final documentReference = id != null
          ? findDocRef(id: id, collectionPathOverride: collectionPathOverride)
          : _firebaseFirestore
              .collection(collectionPathOverride ?? _collectionPath())
              .doc();
      _log.value(documentReference.id, '🔥 Document ID');
      _log.info('🔥 Creating JSON..');
      final writeableAsJson = (merge || mergeFields != null) &&
              (await documentReference.get(_getOptions)).exists
          ? updateTimeStampType.add(
              writeable.toJson(),
              updatedFieldName: _updatedFieldName,
              createdFieldName: _createdFieldName,
            )
          : createTimeStampType.add(
              writeable.toJson(),
              createdFieldName: _createdFieldName,
              updatedFieldName: _updatedFieldName,
            );
      _log.value(writeableAsJson, '🔥 JSON');
      _log.info('🔥 Setting data with writeBatch.set..');
      nullSafeWriteBatch.set(
        documentReference,
        writeableAsJson,
        SetOptions(
          merge: mergeFields == null ? merge : null,
          mergeFields: mergeFields,
        ),
      );
      _log.success(
          '🔥 Adding create 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 create ${collectionPathOverride ?? _collectionPath()} document with '
      'id: $id, '
      'writeBatch: $writeBatch, '
      'createTimeStampType: ${createTimeStampType.name}, '
      'updateTimeStampType: ${updateTimeStampType.name}, '
      'merge: $merge, '
      'mergeFields: $mergeFields..',
      error: error,
      stackTrace: stackTrace,
    );
    return _responseConfig.createFailedResponse(isPlural: true);
  }
}