登录
首页 >  Golang >  Go问答

在golang SDK中如何在firestore事务中传递数据?

来源:stackoverflow

时间:2024-03-20 13:18:32 385浏览 收藏

在 Firestore 事务中,Java SDK 允许传递信息,而 Go SDK 似乎缺少此功能。在 Java 中,可以使用 Future 对象检索事务的返回结果,而 Go SDK 目前只返回错误。本文将提供一个 Go SDK 解决方案,通过在外部作用域中声明变量并在事务中对其进行分配,实现从事务中返回一个值。

问题内容

我想从 golang 中的 firestore 事务中传递信息。

这在此处记录[src-java]。

如果我们看例如在java代码中,它看起来像这样:

final documentreference docref = db.collection("cities").document("sf");
apifuture futuretransaction = db.runtransaction(transaction -> {
  documentsnapshot snapshot = transaction.get(docref).get();
  long newpopulation = snapshot.getlong("population") + 1;
  if (newpopulation <= 1000000l) {
    transaction.update(docref, "population", newpopulation);
    return "population increased to " + newpopulation;
  } else {
    throw new exception("sorry! population is too big.");
  }
});
system.out.println(futuretransaction.get());   // [me] <-- this is a  future, so it can return both a value and an error
managedatasnippets.java

另一方面,go 代码如下所示 [src-go]:

ref := client.Collection("cities").Doc("SF")

// ↓↓↓ [me] only `err` is returned here, no "positive" value
err := client.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
        doc, err := tx.Get(ref)
        if err != nil {
                return err
        }
        pop, err := doc.DataAt("population")
        if err != nil {
                return err
        }
        newpop := pop.(int64) + 1
        if newpop <= 1000000 {
                return tx.Set(ref, map[string]interface{}{
                        "population": pop.(int64) + 1,
                }, firestore.MergeAll)
        }
        return errors.New("population is too big")
})
if err != nil {
        log.Printf("An error has occurred: %s", err)
}

是否可以从golang中的firestore事务返回一个值,或者go sdk是否缺少此功能?我关注了其他语言,如 python、swift、js,看起来它们也允许从交易中返回“正”值。


解决方案


在外部作用域中声明变量。分配给事务中的变量。

var newpop int64  // <-- declaration

err := client.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
        doc, err := tx.Get(ref)
        if err != nil {
                return err
        }
        pop, err := doc.DataAt("population")
        if err != nil {
                return err
        }
        newpop = pop.(int64) + 1 // <-- short var decl changed to assignment
        if newpop <= 1000000 {
                return tx.Set(ref, map[string]interface{}{
                        "population": newpop,
                }, firestore.MergeAll)
        }
        return errors.New("population is too big")
})
if err != nil {
        log.Printf("An error has occurred: %s", err)
}

log.Print("the new pop is", newpop)

好了,本文到此结束,带大家了解了《在golang SDK中如何在firestore事务中传递数据?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>