createDoc method

Future<FeedbackResponse<DocumentReference<Object?>>> createDoc({
  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,
  9. Transaction? transaction,
})

Creates/writes data based on given writeable.

Passing in an id will give your document that id.

Passing in a writeBatch will close the WriteBatch and perform the last commit. If you want to add more to your WriteBatch then use the batchCreateDoc method instead.

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.

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

Implementation

Future<FeedbackResponse<DocumentReference>> createDoc({
  required Writeable writeable,
  String? id,
  WriteBatch? writeBatch,
  TimestampType createTimeStampType = TimestampType.createdAndUpdated,
  TimestampType updateTimeStampType = TimestampType.updated,
  bool merge = false,
  List<FieldPath>? mergeFields,
  String? collectionPathOverride,
  Transaction? transaction,
}) 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 {
    _log.info('🔥 Checking if writeable is valid..');
    final isValidResponse = writeable.isValidResponse();
    if (isValidResponse.isSuccess) {
      _log.success('🔥 Writeable is valid!');
      _log.info(
        '🔥 '
        'Creating ${collectionPathOverride ?? _collectionPath()} document with '
        'writeable: $writeable, '
        'id: $id, '
        'writeBatch: $writeBatch, '
        'createTimeStampType: ${createTimeStampType.name}, '
        'updateTimeStampType: ${updateTimeStampType.name}, '
        'merge: $merge, '
        'mergeFields: $mergeFields..',
      );
      final DocumentReference documentReference;
      if (writeBatch != null) {
        _log.info('🔥 WriteBatch was not null! Creating with batch..');
        final lastBatchResponse = await batchCreateDoc(
          writeable: writeable,
          id: id,
          writeBatch: writeBatch,
          createTimeStampType: createTimeStampType,
          updateTimeStampType: updateTimeStampType,
          collectionPathOverride: collectionPathOverride,
          merge: merge,
          mergeFields: mergeFields,
        );
        _log.info('🔥 Checking if batchCreate was successful..');
        if (lastBatchResponse.isSuccess) {
          final writeBatchWithReference = lastBatchResponse.result!;
          _log.info('🔥 Last batch was added with success! Committing..');
          await writeBatchWithReference.writeBatch.commit();
          _log.success('🔥 Committing writeBatch done!');
          documentReference = writeBatchWithReference.documentReference;
        } else {
          _log.error('🔥 Last batch failed!');
          return _responseConfig.createFailedResponse(isPlural: true);
        }
      } else {
        _log.info('🔥 WriteBatch was null! Creating without batch..');
        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()).exists
                ? updateTimeStampType.add(
                    writeable.toJson(),
                    updatedFieldName: _updatedFieldName,
                  )
                : createTimeStampType.add(
                    writeable.toJson(),
                    createdFieldName: _createdFieldName,
                    updatedFieldName: _updatedFieldName,
                  );
        _log.value(writeableAsJson, '🔥 JSON');
        var setOptions = SetOptions(
          merge: mergeFields == null ? merge : null,
          mergeFields: mergeFields,
        );
        if (transaction == null) {
          _log.info('🔥 Setting data with documentReference.set..');
          await documentReference.set(
            writeableAsJson,
            setOptions,
          );
        } else {
          _log.info('🔥 Setting data with transaction.set..');
          transaction.set(
            findDocRef(id: documentReference.id),
            writeableAsJson,
            setOptions,
          );
        }
      }
      _log.success('🔥 Setting data done!');
      return _responseConfig.createSuccessResponse(
        isPlural: writeBatch != null,
        result: 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 '
      'writeable: $writeable, '
      'id: $id, '
      'writeBatch: $writeBatch, '
      'createTimeStampType: ${createTimeStampType.name}, '
      'updateTimeStampType: ${updateTimeStampType.name}, '
      'merge: $merge, '
      'mergeFields: $mergeFields..',
      error: error,
      stackTrace: stackTrace,
    );
    return _responseConfig.createFailedResponse(isPlural: writeBatch != null);
  }
}