-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirestore.go
87 lines (70 loc) · 1.67 KB
/
firestore.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
87
package firebase
import (
"context"
"encoding/json"
"log"
"os"
"sync"
"cloud.google.com/go/firestore"
"google.golang.org/api/option"
U "github.com/off-chain-storage/comparing-offchain-firebase/utils"
)
type FirestoreDB struct {
client *firestore.Client
}
var dbInstance *FirestoreDB
var once sync.Once
func DBClient() *firestore.Client {
once.Do(func() {
dbInstance = new(FirestoreDB)
makeDBClient(dbInstance)
})
return dbInstance.client
}
func makeDBClient(rtb *FirestoreDB) {
// Init FireStore SDK
opt := option.WithCredentialsFile(os.Getenv("GOOGLE_APPLICATION_CREDENTIALS"))
ctx := context.Background()
client, err := firestore.NewClient(
ctx, os.Getenv("FIREBASE_FIRESTORE_DATABASE_PRODUCT_ID"), opt)
if err != nil {
log.Fatal(err)
}
// defer client.Close()
rtb.client = client
}
func CreateDoc() {
ctx := context.Background()
client := DBClient()
_, err := client.Doc("User/User13818").Create(ctx, map[string]interface{}{
"Index": 1,
"Gender": "M",
"UserID": "bum0448",
"Name": "jinbumjinbum",
})
U.CheckErr(err)
}
func UpdateDoc() {
ctx := context.Background()
client := DBClient()
if _, err := client.Doc("User/User13818").
Update(ctx, []firestore.Update{
{"FlagColor", nil, "Red"},
{Path: "Location", Value: "Middle"}}); err != nil {
log.Fatalf("Update error: %s\n", err)
}
}
func ReadDoc() {
ctx := context.Background()
client := DBClient()
state, err := client.Doc("User/User13818").Get(ctx)
U.CheckErr(err)
_, err = json.MarshalIndent(state.Data(), "", " ")
U.CheckErr(err)
}
func DeleteDoc() {
ctx := context.Background()
client := DBClient()
_, err := client.Doc("User/User13818").Delete(ctx)
U.CheckErr(err)
}