update method
Updates an existing item in the repository.
Implementation
@override
Future<T> update(String id, T Function(T current) updater) async {
final doc = store.doc(_normaliseToFullPath(id));
final snapshot = await doc.get();
final existingData = snapshot.data();
if (existingData == null) {
throw RepositoryException.notFound(id);
}
final current = fromFirestore(
snapshot.reference,
RepositoryFirestore.typeConversionFromFirebase.convert(source: existingData),
);
final updated = toFirestore(updater(current));
final updatedJson = RepositoryFirestore.typeConversionToFirebase.convert(source: updated);
final existingJson = RepositoryFirestore.typeConversionToFirebase.convert(source: existingData);
final changedFields = <String, dynamic>{};
for (final entry in updatedJson.entries) {
if (existingJson[entry.key] != entry.value) {
changedFields[entry.key] = entry.value;
}
}
if (changedFields.isNotEmpty) {
await doc.update(changedFields);
}
final finalSnapshot = await doc.get();
final finalData = finalSnapshot.data();
if (finalData == null) {
throw RepositoryException.notFound(id);
}
return fromFirestore(
finalSnapshot.reference,
RepositoryFirestore.typeConversionFromFirebase.convert(source: finalData),
);
}