在Firebase中使用交易 [英] Using transactions in Firebase

查看:77
本文介绍了在Firebase中使用交易的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目应用程序中,我同时使用Firebase存储和数据库.我想使用事务处理概念,但是我以前从未使用过它,因此对我来说并不明显. 允许用户将文件上传到服务器.我在数据库中跟踪这些上载(将上载文件的url分配给用户).因此,我同时执行2个操作:

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

更新数据库

我想确定如果这些操作中的任何一个失败,则不会执行任何操作(例如,Internet连接断开).我需要一些技巧来处理如前所述的异常,以及如何在当前崩溃时以适当的方式实现它.这是我的代码:

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)
 }
}

提前谢谢!

推荐答案

事务仅在启动事务的数据库上下文中运行.事务的全有或无"行为仅适用于您在数据库本身内完成的工作,而不适用于任何外部属性.您的事务处理程序应尽可能快,并且不要阻塞其他工作.

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.

这篇关于在Firebase中使用交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆