0

Recently I have been developing an app which requires the following code:

/** Unfriends the user with the specified UID */
func removeFriend(_ userID: String, completion: CompletionHandler? = nil) {
    CURRENT_USER_FRIENDS_REF.document(userID).delete { (error) in
        guard error == nil else{
            completion?(error)
            return
        }

        self.users.document(userID).collection(NameFile.Firebase.UserDB.friends).document(AppStorage.PersonalInfo.uid).delete(completion: completion)
    }
}

The problem arises in nesting these blocks. If the first blocks succeeds, but the second block throws an error, the completion handler will be passed an error. However, in reality, half the process succeeded and wrote successfully to database. Is it possible to have both these blocks work together as one block which passes an error if an error occurs. (without restructuring the database)

Nikhil Sridhar
  • 1,670
  • 5
  • 20
  • 39

1 Answers1

2

If you have multiple write operations that must either call succeed or all fail, you should use a transaction or batched write. The difference between the two is whether you need the current value of a document to determine its new value. If you don't need the current value for any document, use a batched write. If you do need the current value for a document, use a transaction for all writes.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807