getDocument<T> method

Future<T?> getDocument<T>(
  1. List<String> paths, {
  2. required String logReference,
  3. required T? onDocumentSnapshot(
    1. DocumentSnapshot<Object?> documentSnapshot
    ),
})

Retrieves a document from Firestore.

paths is the list of paths to the document. For example: myCollection, documentId which will be constructed to myCollection/documentId. logReference is reference string for logging purposes so we know when this query gets executed and what executes it. onDocumentSnapshot is a method with return type of an object.

Implementation

Future<T?> getDocument<T>(
  List<String> paths, {
  required String logReference,
  required T? Function(DocumentSnapshot documentSnapshot) onDocumentSnapshot,
}) async {
  final pathToDocument = getPathToDocument(paths);

  try {
    _loggingService.log('FirestoreHelper.getDocument.$logReference: Path: $pathToDocument');
    final documentSnapshot = await _firebaseFirestore.doc(pathToDocument).get();
    if (!documentSnapshot.exists) {
      _loggingService.log(
        'FirestoreHelper.getDocument.$logReference: Path: $pathToDocument. Document does not exist',
        logType: LogType.warning,
      );
      return null;
    }

    final element = onDocumentSnapshot(documentSnapshot);

    return element;
  } catch (e, s) {
    _loggingService.log(
      'FirestoreHelper.getDocument.$logReference: Path: $pathToDocument, Exception: $e. StackTrace: $s',
      logType: LogType.error,
    );
    return null;
  }
}