-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtransaction-readonly.go
68 lines (56 loc) · 1.37 KB
/
transaction-readonly.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
"github.com/sanity-io/litter"
"google.golang.org/genproto/googleapis/type/latlng"
)
type Customer struct {
ID string
Name string
// Location is a point on the earth
// it MUST be a pointer to saved as the right type in Firestore
Location *latlng.LatLng
}
type User struct {
ID string
Name string
}
func main() {
ctx := context.Background()
client, cerr := firestore.NewClient(ctx, "firestore-and-go")
if cerr != nil {
panic(cerr)
}
// START TRANSACTION OMIT
// Create a new customer and new user in the customer in one transaction
custRef := client.Collection("customers").Doc("ut-gophers")
userRef := custRef.Collection("users").Doc("carsonoid")
err := client.RunTransaction(ctx, func(ctx context.Context, t *firestore.Transaction) error {
custSnap, err := t.Get(custRef)
if err != nil {
return err
}
userSnap, err := t.Get(userRef)
if err != nil {
return err
}
fmt.Println("The Docs look like this right now:")
fmt.Println(custSnap.Data())
fmt.Println(userSnap.Data())
return nil
}, firestore.ReadOnly) // Run the transaction in readonly mode
if err != nil {
panic(err)
}
// END TRANSACTION OMIT
}
func dumpDoc(docSnapshot *firestore.DocumentSnapshot) {
user := &User{}
err := docSnapshot.DataTo(user)
if err != nil {
panic(err)
}
litter.Dump(user)
}