要删除我的应用程序中的分类广告,我有一个两步过程,其中包括:
我希望它成为同一事务的一部分,并且是原子的。
我知道一个事务可以根据
get
运行多次,而这些都必须在开头:这让我很困惑,因为我不会拥有新创建的文档的多个副本。
因此,我希望您能帮助我展示如何做到这一点?
我现有的代码如下:
// Deletes the ad or throw an error if it does not exist or if an error occured
Future<void> transactionStoreDelete() async {
final fs = FirebaseFirestore.instance;
// == Move assets to to-be-deleted collections for future actual removal
// from our servers and services
// Note that if we do not succeed at moving the video assets to the
// collection, there would be a yet-to-be-delvelopped server worker that
// find unreferenced video and stream assets that will remove them from the
// cloud and our services.
try {
await storeMarkVideoAndStreamToBeDeleted();
await FirebaseFirestore.instance.runTransaction((t) async {
/// Reads the ad document
final doc = await t.get(fs.collection(collectionName).doc(id));
if (doc.exists) {
t.delete(doc.reference);
}
});
} catch (e) {
debugPrint(
"Could not move video assets to to-be-deleted collections: $e");
}
}
其中
storeMarkVideoAndStreamToBeDeleted
如下:
/// Clean up video assets byt doing the following:
/// 1) Move the video and video stream to the to-be-deleted related collections;
/// 2) Nullify [videoUrl] and [stream] in the current ad instance;
/// 3) Update the ad in the collection.
///
Future<void> storeMarkVideoAndStreamToBeDeleted() async {
if (videoUrl != null) {
try {
// == Create record set in to be delted video
await FirebaseFirestore.instance.collection("toBeDeletedVideos").add({
...trackingInformation,
"url": videoUrl!,
});
} catch (e) {
debugPrint("Could not move the video to be deleted: $e");
}
}
if (stream != null) {
try {
// == Create record set in to be deleted stream
await FirebaseFirestore.instance.collection("toBeDeletedStreams").add({
...trackingInformation,
"streamId": stream!.id,
});
} catch (e) {
debugPrint("Could not move the stream video to be deleted: $e");
}
}
// == Now erase reference to them
return FirebaseFirestore.instance
.collection(collectionName)
.doc(id)
.update({
"videoUrl": null,
"stream": null,
});
}