因此,我的应用程序中有一个“删除帐户”按钮,当用户点击它时,它将删除Auth帐户以及其他3个Firestore文档。我担心一个功能可能成功而其他功能可能失败。如何确保如果一项功能失败,所有功能都会失败?
func deleteUser () {
let currentUser = Auth.auth().currentUser
Auth.auth().currentUser?.delete(completion: { (error) in
if error != nil { return }
else {
Firestore.firestore().collection("Users").document(currentUser!.uid).delete { (error) in
if error != nil { return }
else {
Firestore.firestore().collection("Posts").document(currentUser!.uid).delete { (error) in
if error != nil { return }
else {
transitionToHomeScreen()
}
}
}
}
}
})
}
What you're looking for is called a transaction. See https://firebase.google.com/docs/firestore/manage-data/transactions.
首先,您可能应该在删除用户之前删除文档。如果首先删除用户,则根据您的安全规则允许,用户可能会失去删除其文档的能力。
其次,无法确保Firebase Auth和Firestore之间(以及任意两个Firebase产品之间)的事务一致性。如果Firestore中发生故障,则无法自动将更改回滚到Auth,反之亦然。如果需要回滚更改,则必须为此编写代码。
If you want to ensure that more than one documents are deleted at the same time, you should use a transaction or batch write to ensure that either all or none of the documents are deleted together.