Skip to content

Commit

Permalink
docs(samples): passing data out of firestore transaction in go
Browse files Browse the repository at this point in the history
  • Loading branch information
myproblemchild authored and subfuzion committed Jul 24, 2024
1 parent d60ee3d commit 82bdfd0
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
2 changes: 1 addition & 1 deletion firestore/save_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ func TestSave(t *testing.T) {
if err = runSimpleTransaction(ctx, client); err != nil {
t.Fatalf("runSimpleTransaction: %v", err)
}
if err = infoTransaction(ctx, client); err != nil {
if _, err = infoTransaction(ctx, client); err != nil {
t.Fatalf("infoTransaction: %v", err)
}
if err = batchWrite(ctx, client); err != nil {
Expand Down
14 changes: 9 additions & 5 deletions firestore/save_transaction_document_update_conditional.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ import (
"cloud.google.com/go/firestore"
)

func infoTransaction(ctx context.Context, client *firestore.Client) error {
func infoTransaction(ctx context.Context, client *firestore.Client) (int64, error) {
var updatedPop int64
ref := client.Collection("cities").Doc("SF")
err := client.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
doc, err := tx.Get(ref)
Expand All @@ -37,18 +38,21 @@ func infoTransaction(ctx context.Context, client *firestore.Client) error {
}
newpop := pop.(int64) + 1
if newpop <= 1000000 {
return tx.Set(ref, map[string]interface{}{
"population": pop.(int64) + 1,
err := tx.Set(ref, map[string]interface{}{
"population": newpop,
}, firestore.MergeAll)
if err == nil {
updatedPop = newpop
}
return err
}
return errors.New("population is too big")
})
if err != nil {
// Handle any errors in an appropriate way, such as returning them.
log.Printf("An error has occurred: %s", err)
}

return err
return updatedPop, err
}

// [END firestore_transaction_document_update_conditional]

0 comments on commit 82bdfd0

Please sign in to comment.