Using transactions in Firebase

拥有回忆 提交于 2019-12-24 13:47:02

问题


In my project app I use Firebase Storage and Database simultaneously. I would like to use transactions concept, however I have never used it before so it's not obvious for me. Users are allowed to upload a file to the server. I track these uploads in database (assigning url's of the uploaded file to the user). So I perform 2 actions at the same time:

  • uploading the file

  • updating database

I wanna be sure that if any of those actions fails, none is performed (e.g. Internet connection is down). I need some tips on how to handle exceptions like the one mentioned before and how to implement it in appropriate way as it is crashing at the moment. Here is the code I have:

newRef.runTransactionBlock({ (currentData: MutableData) -> 
TransactionResult in
 let uploadTask = ref.putData(contents as Data, metadata: 
  self.myMetadata, completion: { (metadata, error) in
    if error != nil {
        ...
    }
    DataService.instance.usersRef.observeSingleEvent(of: .value) { 
    (snapshot: DataSnapshot) in
        ...
     _ = DataService.instance.usersRef.child("\
     (key)/profile/myURLS").updateChildValues([ strEncoded as! 
     AnyHashable : downloadURL])
    }
 }
 return TransactionResult.success(withValue: currentData)
})
{ (error, committed, snapshot) in
 if let error = error {
   print(error.localizedDescription)
 }
}

Thanks in advance!


回答1:


Transactions only run within the context of the database where the transaction is started. The all-or-none behavior of transactions only applies to the work that you do within the database itself, not any external properties. Your transaction handlers should be as fast as possible and not block on other work.

The usual practice for file uploads is to perform the file upload first, then after that succeeds, write to the database.



来源:https://stackoverflow.com/questions/48772797/using-transactions-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!