-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathitems.go
135 lines (109 loc) · 2.51 KB
/
items.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package main
import (
"encoding/json"
"fmt"
"github.com/stefanhans/gcp-serverless-b8e-play/Play/booking/types"
"google.golang.org/api/iterator"
"log"
)
func AddItem(arguments []string) {
_ = arguments
if client == nil {
fmt.Printf("not connected - use %q\n", "connect")
return
}
collection = "items"
item := types.Item{ID: 1,
Name: "Tesla Deluxe",
Type: types.CAR,
}
jsonRequest, err := json.MarshalIndent(item, "", " ")
if err != nil {
fmt.Printf("failed to marshall 'jsonRequest': %v\n", err)
return
}
fmt.Printf("jsonRequest: %s\n", jsonRequest)
// Declared an empty map interface
var result map[string]interface{}
// Unmarshal or Decode the JSON to the interface.
json.Unmarshal([]byte(string(jsonRequest)), &result)
// [START fs_add_data_1]
_, _, err = client.Collection(collection).Add(ctx, result)
if err != nil {
log.Fatalf("Failed adding document to collection %q: %v", collection, err)
}
iter := client.Collection(collection).Documents(ctx)
for {
doc, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatalf("Failed to iterate: %v", err)
}
fmt.Println(doc.Data())
}
}
func DeleteItems(arguments []string) {
_ = arguments
if client == nil {
fmt.Printf("not connected - use %q\n", "connect")
return
}
collection = "items"
ref := client.Collection(collection)
batchSize := 20
for {
// Get a batch of documents
iter := ref.Limit(batchSize).Documents(ctx)
numDeleted := 0
// Iterate through the documents, adding
// a delete operation for each one to a
// WriteBatch.
batch := client.Batch()
for {
doc, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
fmt.Printf("failed next iteration: %v\n", err)
return
}
batch.Delete(doc.Ref)
numDeleted++
}
// If there are no documents to delete,
// the process is over.
if numDeleted == 0 {
fmt.Printf("all %s deleted\n", collection)
return
}
result, err := batch.Commit(ctx)
if err != nil {
fmt.Printf("failed to commit batch for deletion: %v\n", err)
return
}
_ = result
//fmt.Printf("Commit Result: %v\n", result)
}
}
func GetItems(arguments []string) {
_ = arguments
if client == nil {
fmt.Printf("not connected - use %q\n", "connect")
return
}
collection = "items"
iter := client.Collection(collection).Documents(ctx)
for {
doc, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatalf("Failed to iterate: %v", err)
}
fmt.Println(doc.Data())
}
}