Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Future<List> getFirestoreDataOptimized(bool fetchCache, Query ref, bool filterDeleted, bool filterSubscribed, Event event) async {
- // Get Cache data first if it exists
- List data = [];
- //! START CACHE SYSTEM
- if (fetchCache == true && event.disableCache == false) {
- // Count the number of documents that the query should return from the server
- AggregateQuerySnapshot query = await ref.count().get();
- int correctDocumentCount = query.count ?? 0;
- var snapshot = await ref.getCacheFirst();
- var documents = snapshot.docs.map((s) => s);
- for (QueryDocumentSnapshot element in documents) {
- Map documentData = element.data() as Map<String, dynamic>;
- documentData['documentId'] = element.id;
- data.add(documentData);
- }
- // Check if the number of documents returned from the server is the same as the number of documents in the cache
- debugPrint('DEBUG - Cache document count: ${data.length} - Server document count: $correctDocumentCount');
- if (data.length != correctDocumentCount) {
- List freshData = [];
- debugPrint('DEBUG - Cache ignored due to document count conflict');
- //fetchCache = false;
- var snapshot = await ref.get();
- var documents = snapshot.docs.map((s) => s);
- for (QueryDocumentSnapshot element in documents) {
- Map documentData = element.data() as Map<String, dynamic>;
- documentData['documentId'] = element.id;
- freshData.add(documentData);
- }
- // Overwrite cache data with fresh data
- data = freshData;
- debugPrint('DEBUG - Overwrote cache data with fresh data');
- }
- /// CACHE SYSTEM
- // Check if there is any newer data on the server and get new data if so.
- // Get last timestamp from cached data
- debugPrint('DEBUG - Checking for new data from server to update cache if needed');
- Timestamp lastUpdate = Timestamp(0, 0);
- for (var element in data) {
- if (element.containsKey('updated') && element['documentId'] == AuthService().user!.uid) {
- debugPrint('DEBUG - Cache Timestamp ignored due to potential timestamp conflict with User for ${ref.toString()}');
- }
- // Only use the timestamp if the documentId does not equal UID
- if (element.containsKey('updated') && element['documentId'] != AuthService().user!.uid) {
- if (element['updated'] is Timestamp) {
- Timestamp timeStamp = element['updated'];
- if (timeStamp.compareTo(lastUpdate) >= 0) {
- lastUpdate = timeStamp;
- }
- } else if (element['updated'] == null) {
- // Do nothing
- } else {
- Timestamp newTimeStamp = Timestamp(element['updated'].round(), 0);
- if (newTimeStamp.compareTo(lastUpdate) >= 0) {
- lastUpdate = newTimeStamp;
- }
- }
- }
- }
- List newData = [];
- var updateRef = ref.where('updated', isGreaterThan: lastUpdate);
- var newSnapshot = await updateRef.get();
- var newDocuments = newSnapshot.docs.map((s) => s);
- for (QueryDocumentSnapshot element in newDocuments) {
- Map documentData = element.data() as Map<String, dynamic>;
- documentData['documentId'] = element.id;
- newData.add(documentData);
- }
- // Merge old and new data if there are any new additions or updates
- if (newData.isNotEmpty) {
- for (var newDocument in newData) {
- // Check if it exists in cache data
- if (data.any((element) => element['documentId'] == newDocument['documentId'])) {
- // Replace data with new version from server
- var index = data.indexWhere((element) => element['documentId'] == newDocument['documentId']);
- data[index] = newDocument;
- debugPrint('DEBUG CACHE - Updated cache document with new data from server');
- } else {
- data.add(newDocument);
- debugPrint('DEBUG CACHE - New document added to cache');
- }
- }
- }
- } else {
- var snapshot = await ref.get();
- var documents = snapshot.docs.map((s) => s);
- for (QueryDocumentSnapshot element in documents) {
- Map documentData = element.data() as Map<String, dynamic>;
- documentData['documentId'] = element.id;
- data.add(documentData);
- }
- }
- //! START FILTER SYSTEM
- // Filter data if needed
- if (filterDeleted) {
- List filteredData = [];
- for (var element in data) {
- if (element['deleted'] == false) {
- filteredData.add(element);
- }
- }
- data = filteredData;
- }
- // FIX subscription
- if (filterSubscribed) {
- List filteredData = [];
- for (var element in data) {
- if (element.containsKey('subscribers')) {
- if (element['subscribers'].contains(AuthService().user!.uid)) {
- element['subscribed'] = true;
- debugPrint('Got subscribed document ${element['documentId']}');
- filteredData.add(element);
- }
- }
- }
- // replace data with filtered data to only show subscribed elements
- data = filteredData;
- } else {
- for (var element in data) {
- if (element.containsKey('subscribers')) {
- if (element['subscribers'].contains(AuthService().user!.uid)) {
- element['subscribed'] = true;
- debugPrint('Got subscribed document ${element['documentId']}');
- } else {
- element['subscribed'] = false;
- }
- }
- }
- }
- // Return early if empty
- if (data.isEmpty) {
- return data;
- }
- if (data.first.containsKey('date') && data.first.containsKey('timeStart')) {
- // Sort by date and time
- data.sort((a, b) {
- int compare = a['date'].compareTo(b['date']);
- if (compare == 0) {
- var timeList1 = a['timeStart'].split(':');
- var timeList2 = b['timeStart'].split(':');
- int x = int.parse(timeList1[0]) * 60 + int.parse(timeList1[1]);
- int y = int.parse(timeList2[0]) * 60 + int.parse(timeList2[1]);
- return x.compareTo(y);
- } else {
- return compare;
- }
- });
- } else {
- // Sort by name if no date and time
- if (data.isNotEmpty && data.first.containsKey('name')) {
- data.sort((a, b) {
- return a['name'].compareTo(b['name']);
- });
- }
- }
- return data;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement