Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix docChanges removed, modified and added with proper index values #284

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 6 additions & 2 deletions lib/src/fake_cloud_firestore_instance.dart
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,12 @@ class FakeFirebaseFirestore implements FirebaseFirestore {
final segments = path.split('/');
assert(segments.length % 2 == 1,
'Invalid document reference. Collection references must have an odd number of segments');
return MockCollectionReference(this, path, getSubpath(_root, path),
_docsData, getSubpath(_snapshotStreamControllerRoot, path));
return MockCollectionReference<Map<String, dynamic>>(
this,
path,
getSubpath(_root, path),
_docsData,
getSubpath(_snapshotStreamControllerRoot, path));
}

@override
Expand Down
5 changes: 4 additions & 1 deletion lib/src/fake_converted_query.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// ignore: subtype_of_sealed_class
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fake_cloud_firestore/src/query_snapshot_stream_manager.dart';

import 'converter.dart';
import 'fake_query_with_parent.dart';
Expand All @@ -26,10 +27,12 @@ class FakeConvertedQuery<T extends Object?> extends FakeQueryWithParent<T> {
toFirestore: _converter.toFirestore)
.get())
.toList();
return MockQuerySnapshot(
final snapshot = MockQuerySnapshot(
await Future.wait(convertedSnapshots),
options?.source == Source.cache,
);
QuerySnapshotStreamManager().setCacheQuerySnapshot(this, snapshot);
return snapshot;
}

@override
Expand Down
11 changes: 7 additions & 4 deletions lib/src/mock_collection_reference.dart
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,15 @@ class MockCollectionReference<T extends Object?> extends MockQuery<T>
return documentReference.get();
}).toList();
}
return MockQuerySnapshot<T>(
final snapshot = MockQuerySnapshot<T>(
(await Future.wait(futureDocs))
.where((snapshot) =>
_firestore.hasSavedDocument(snapshot.reference.path))
.toList(),
options?.source == Source.cache,
);
QuerySnapshotStreamManager().setCacheQuerySnapshot(this, snapshot);
KholmatovS marked this conversation as resolved.
Show resolved Hide resolved
return snapshot;
}

List<Future<DocumentSnapshot<T>>> _buildDocumentsForCollectionGroup(
Expand Down Expand Up @@ -132,7 +134,7 @@ class MockCollectionReference<T extends Object?> extends MockQuery<T>
DocumentReference<T> _documentReference(
String collectionFullPath, String id, Map<String, dynamic> root) {
final fullPath = [collectionFullPath, id].join('/');
final rawDocumentReference = MockDocumentReference<Map<String, dynamic>>(
final rawDocumentReference = MockDocumentReference<T>(
_firestore,
fullPath,
id,
Expand All @@ -144,7 +146,7 @@ class MockCollectionReference<T extends Object?> extends MockQuery<T>
);
if (_converter == null) {
// Since there is no converter, we know that T is Map<String, dynamic>.
return rawDocumentReference as DocumentReference<T>;
return rawDocumentReference;
}
// Convert.
final convertedDocumentReference = rawDocumentReference.withConverter(
Expand All @@ -158,7 +160,8 @@ class MockCollectionReference<T extends Object?> extends MockQuery<T>
final documentReference = doc();
await documentReference.set(data);
_firestore.saveDocument(documentReference.path);
await QuerySnapshotStreamManager().fireSnapshotUpdate(firestore, path);
await QuerySnapshotStreamManager()
.fireSnapshotUpdate<T>(firestore, path, id: documentReference.id);
return documentReference;
}

Expand Down
6 changes: 4 additions & 2 deletions lib/src/mock_document_reference.dart
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,8 @@ class MockDocumentReference<T extends Object?>
_applyValues(document, key, value);
});
_firestore.saveDocument(path);
await QuerySnapshotStreamManager().fireSnapshotUpdate(firestore, path);
await QuerySnapshotStreamManager()
.fireSnapshotUpdate<T>(firestore, path, id: id);
fireSnapshotUpdate();
return Future.value(null);
}
Expand Down Expand Up @@ -277,7 +278,8 @@ class MockDocumentReference<T extends Object?>
_firestore.removeSavedDocument(path);
docsData.remove(path);
// Notify on the parent collection.
await QuerySnapshotStreamManager().fireSnapshotUpdate(firestore, path);
await QuerySnapshotStreamManager()
.fireSnapshotUpdate<T>(firestore, path, id: id);
// Notify the document listeners.
fireSnapshotUpdate();
return Future.value();
Expand Down
6 changes: 5 additions & 1 deletion lib/src/mock_query.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:math';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fake_cloud_firestore/src/query_snapshot_stream_manager.dart';
import 'package:fake_cloud_firestore/src/util.dart';
import 'package:flutter/services.dart';
import 'package:mock_exceptions/mock_exceptions.dart';
Expand Down Expand Up @@ -43,7 +44,10 @@ class MockQuery<T extends Object?> extends FakeQueryWithParent<T> {
maybeThrowException(this, Invocation.method(#get, [options]));
final parentQueryResult = await _parentQuery!.get(options);
final docs = _operation!(parentQueryResult.docs);
return MockQuerySnapshot<T>(docs, options?.source == Source.cache);
final snapshot =
MockQuerySnapshot<T>(docs, options?.source == Source.cache);
QuerySnapshotStreamManager().setCacheQuerySnapshot(this, snapshot);
return snapshot;
}

@override
Expand Down
31 changes: 17 additions & 14 deletions lib/src/mock_query_snapshot.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fake_cloud_firestore/src/mock_document_change.dart';
import 'package:fake_cloud_firestore/src/mock_snapshot_metadata.dart';

import 'mock_document_change.dart';
import 'mock_query_document_snapshot.dart';

class MockQuerySnapshot<T extends Object?> implements QuerySnapshot<T> {
Expand All @@ -14,19 +14,22 @@ class MockQuerySnapshot<T extends Object?> implements QuerySnapshot<T> {

MockQuerySnapshot(
this._docSnapshots,
bool isFromCache,
) : metadata = MockSnapshotMetadata(isFromCache: isFromCache) {
// TODO: support another change type (removed, modified).
// ref: https://pub.dev/documentation/cloud_firestore_platform_interface/latest/cloud_firestore_platform_interface/DocumentChangeType-class.html
_docSnapshots.asMap().forEach((index, docSnapshot) {
_documentChanges.add(MockDocumentChange<T>(
docSnapshot,
DocumentChangeType.added,
oldIndex:
-1, // See: https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/DocumentChange/oldIndex.html
newIndex: index,
));
});
bool isFromCache, {
final List<DocumentChange<T>>? documentChanges,
}) : metadata = MockSnapshotMetadata(isFromCache: isFromCache) {
if (documentChanges != null) {
_documentChanges.addAll(documentChanges);
} else {
_docSnapshots.asMap().forEach((index, docSnapshot) {
_documentChanges.add(MockDocumentChange<T>(
docSnapshot,
DocumentChangeType.added,
oldIndex: -1,
// See: https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/DocumentChange/oldIndex.html
newIndex: index,
));
});
}
}

@override
Expand Down
102 changes: 97 additions & 5 deletions lib/src/query_snapshot_stream_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:rxdart/rxdart.dart';

import 'fake_query_with_parent.dart';
import 'mock_document_change.dart';
import 'mock_query_snapshot.dart';

/// This class maintains stream controllers for Queries to fire snapshots.
class QuerySnapshotStreamManager {
Expand All @@ -13,12 +15,15 @@ class QuerySnapshotStreamManager {
_instance ??= QuerySnapshotStreamManager._internal();

QuerySnapshotStreamManager._internal();

final Map<
FirebaseFirestore,
Map<String,
Map<FakeQueryWithParent, StreamController<QuerySnapshot>>>>
_streamCache = {};

final Map<FakeQueryWithParent, QuerySnapshot> _cacheQuerySnapshot = {};

Future<void> clear() {
final streamCloseFutures = <Future>[];
for (final pathToQueryToStreamController in _streamCache.values) {
Expand All @@ -30,6 +35,7 @@ class QuerySnapshotStreamManager {
}
}
_streamCache.clear();
_cacheQuerySnapshot.clear();
return Future.wait(streamCloseFutures);
}

Expand Down Expand Up @@ -81,25 +87,111 @@ class QuerySnapshotStreamManager {
return streamController;
}

Future<void> fireSnapshotUpdate(
FirebaseFirestore firestore, String path) async {
Future<void> fireSnapshotUpdate<T>(
FirebaseFirestore firestore,
String path, {
String? id,
}) async {
if (!_streamCache.containsKey(firestore)) {
// Normal. It happens if you try to fire updates before anyone has
// subscribed to snapshots.
return;
}
final exactPathCache = _streamCache[firestore]![path];
if (exactPathCache != null) {
if (exactPathCache != null && id != null) {
for (final query in [...exactPathCache.keys]) {
await query.get().then(exactPathCache[query]!.add);
if (query is! FakeQueryWithParent<T>) {
continue;
}

final invalidCache = _cacheQuerySnapshot[query] != null &&
_cacheQuerySnapshot[query] is! QuerySnapshot<T>;
if (invalidCache) {
assert(invalidCache,
'querySnapshotPrior is not null or QuerySnapshot<T>. Got ${_cacheQuerySnapshot[query]}');
continue;
}
final querySnapshotPrior =
_cacheQuerySnapshot[query] as QuerySnapshot<T>?;

final querySnapshot = await query.get();
final docsPrior = querySnapshotPrior?.docs ?? [];
final docsCurrent = List.of(querySnapshot.docs);

final docChange = _getDocumentChange<T>(
id: id,
docsPrior: docsPrior,
docsCurrent: docsCurrent,
);

final documentsChange = <DocumentChange<T>>[];

if (docChange != null) {
documentsChange.add(docChange);
}
final querySnapshotCurrent = MockQuerySnapshot<T>(
docsCurrent,
querySnapshot.metadata.isFromCache,
documentChanges: documentsChange,
);
exactPathCache[query]?.add(querySnapshotCurrent);
}
}

// When a document is modified, fire an update on the parent collection.
if (path.contains('/')) {
final tokens = path.split('/');
final parentPath = tokens.sublist(0, tokens.length - 1).join('/');
await fireSnapshotUpdate(firestore, parentPath);
await fireSnapshotUpdate<T>(firestore, parentPath, id: id ?? tokens.last);
}
}

/// Returns [DocumentChange] for doc [id] based on the change between [docsPrior] and [docsCurrent].
DocumentChange<T>? _getDocumentChange<T>({
required String id,
required List<QueryDocumentSnapshot<T>> docsPrior,
required List<QueryDocumentSnapshot<T>> docsCurrent,
}) {
final docPriorIndex = docsPrior.indexWhere((element) {
return element.id == id;
});
final docCurrentIndex = docsCurrent.indexWhere((element) {
return element.id == id;
});

if (docCurrentIndex != -1 && docPriorIndex != -1) {
/// Document is modified.
return MockDocumentChange<T>(
docsCurrent[docCurrentIndex],
DocumentChangeType.modified,
oldIndex: docPriorIndex,
newIndex: docCurrentIndex,
);
} else if (docCurrentIndex != -1 && docPriorIndex == -1) {
/// Document is added.
return MockDocumentChange<T>(
docsCurrent[docCurrentIndex],
DocumentChangeType.added,
oldIndex: -1,
newIndex: docCurrentIndex,
);
} else if (docCurrentIndex == -1 && docPriorIndex != -1) {
/// Document is removed.
return MockDocumentChange<T>(
docsPrior[docPriorIndex],
DocumentChangeType.removed,
oldIndex: docPriorIndex,
newIndex: -1,
);
}
return null;
}

/// Updates the latest cached [QuerySnapshot] for [query] stored in [_cacheQuerySnapshot].
void setCacheQuerySnapshot<T>(
FakeQueryWithParent query,
QuerySnapshot<T> querySnapshot,
) {
_cacheQuerySnapshot[query] = querySnapshot;
}
}