-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirebase.go
86 lines (72 loc) · 1.95 KB
/
firebase.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"context"
"fmt"
"log"
"time"
"cloud.google.com/go/firestore"
firebase "firebase.google.com/go"
"google.golang.org/api/option"
)
func database(data int) {
// Get the database initalized
client, ctx, err := FirebaseInstance()
if err != nil {
panic(err)
}
// Simple counter
//var counter int
for {
// Example read of data
fmt.Printf("data value %v\n", data)
dsnap, err := client.Collection("orders").Doc("example").Get(ctx)
if err != nil {
panic(err)
}
var order Order
dsnap.DataTo(&order)
fmt.Printf("Read Document data: %#v\n", order)
// Wait some period of time
time.Sleep(time.Second * 2)
//fmt.Printf("Increasing old Weight form %v to %v\n", order.Weight, counter)
fmt.Printf("Update old Weight from %v to %v\n", order.Weight, data)
// Update counter from the database
order.Weight = data
// Wait some period of time
time.Sleep(time.Second * 2)
// Example write of data
_, err = client.Collection("orders").Doc("example").Update(ctx, []firestore.Update{
{
Path: "weight",
//Value: counter,
Value: data,
},
})
if err != nil {
// Handle any errors in an appropriate way, such as returning them.
panic(err)
} else {
fmt.Println("Updated document in database")
}
// Wait some period of time
time.Sleep(time.Second * 3)
return
}
}
// FirebaseInstance obtains the client and ctx when needed
func FirebaseInstance() (*firestore.Client, context.Context, error) {
// Get static variables for setting up the firestore
var opt = option.WithCredentialsFile("private/smart-scale-4207c-firebase-adminsdk-dtl6f-6878a5d23b.json")
var config = &firebase.Config{ProjectID: "smart-scale-4207c"}
// Setup the FireStore data
ctx := context.Background()
app, err := firebase.NewApp(ctx, config, opt)
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
}
client, err := app.Firestore(ctx)
if err != nil {
return nil, ctx, err
}
return client, ctx, nil
}