getDocuments<T> method
Retrieves list of documents from Firestore. It simplifies pagination flow, so services doesn't need to contain boilerplate code.
query
is the query used for the firestore.
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.
lastDocumentSnapshot
must not be null if pagination is required as it is an indicator of where to
continue query.
Implementation
Future<List<T>?> getDocuments<T>({
required Query query,
required String logReference,
required T? Function(DocumentSnapshot documentSnapshot) onDocumentSnapshot,
DocumentSnapshot? lastDocumentSnapshot,
}) async {
final isMoreQuery = lastDocumentSnapshot != null;
final currentQuery = isMoreQuery ? query.startAfterDocument(lastDocumentSnapshot) : query;
_loggingService.log('FirestoreHelper.getDocuments.$logReference: More: $isMoreQuery, Query: ${currentQuery.parameters}');
try {
final querySnapshot = await currentQuery.get();
final elements = querySnapshot.docs.map((e) => onDocumentSnapshot(e)).toList();
_loggingService.log('FirestoreHelper.getDocuments.$logReference: Total: ${elements.length}');
return List<T>.from(elements.where((element) => element != null));
} catch (e, s) {
_loggingService.log(
'FirestoreTransactionsService.getDocuments: Exception: $e. StackTrace: $s',
logType: LogType.error,
);
return null;
}
}