forked from sagikazarmark/crypt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
firestore.go
121 lines (105 loc) · 2.51 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
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
package firestore
import (
"context"
"errors"
"time"
"cloud.google.com/go/firestore"
"github.com/xl1605368195/crypt/backend"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/grpc"
)
type Client struct {
client *firestore.Client
}
type data struct {
Data []byte `firestore:"data"`
}
func New(machines []string) (*Client, error) {
if len(machines) == 0 {
return nil, errors.New("project should be defined")
}
opts := []option.ClientOption{
option.WithGRPCDialOption(grpc.WithBlock()),
}
c, err := firestore.NewClient(context.TODO(), machines[0], opts...)
if err != nil {
return nil, err
}
return &Client{c}, nil
}
func (c *Client) Get(path string) ([]byte, error) {
return c.GetWithContext(context.TODO(), path)
}
func (c *Client) GetWithContext(ctx context.Context, path string) ([]byte, error) {
snap, err := c.client.Doc(path).Get(ctx)
if err != nil {
return nil, err
}
d := &data{}
err = snap.DataTo(&d)
if err != nil {
return nil, err
}
return d.Data, nil
}
func (c *Client) List(collection string) (backend.KVPairs, error) {
return c.ListWithContext(context.TODO(), collection)
}
func (c *Client) ListWithContext(ctx context.Context, collection string) (backend.KVPairs, error) {
res := backend.KVPairs{}
it := c.client.Collection(collection).Documents(ctx)
for {
doc, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
d := &data{}
err = doc.DataTo(&d)
if err != nil {
return nil, err
}
res = append(res, &backend.KVPair{
Key: doc.Ref.ID,
Value: d.Data,
})
}
return res, nil
}
func (c *Client) Set(path string, value []byte) error {
return c.SetWithContext(context.TODO(), path, value)
}
func (c *Client) SetWithContext(ctx context.Context, path string, value []byte) error {
_, err := c.client.Doc(path).Set(ctx, &data{value})
return err
}
func (c *Client) Watch(path string, stop chan bool) <-chan *backend.Response {
return c.WatchWithContext(context.TODO(), path, stop)
}
func (c *Client) WatchWithContext(ctx context.Context, path string, stop chan bool) <-chan *backend.Response {
ch := make(chan *backend.Response, 0)
t := time.NewTicker(time.Second)
go func() {
for {
select {
case <-t.C:
v := &data{}
snap, err := c.client.Doc(path).Get(ctx)
if err == nil {
err = snap.DataTo(&v)
}
ch <- &backend.Response{v.Data, err}
if err != nil {
time.Sleep(time.Second * 5)
}
case <-stop:
close(ch)
return
}
}
}()
return ch
}