-
Notifications
You must be signed in to change notification settings - Fork 5
/
client.go
75 lines (68 loc) · 1.81 KB
/
client.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
package fstore
import (
"cloud.google.com/go/firestore"
"context"
"errors"
"google.golang.org/api/iterator"
"gopkg.in/oauth2.v3/models"
"sync"
"time"
)
type store struct {
s sync.Mutex
c *firestore.Client
n string // Top-level collection name.
t time.Duration
}
func (s *store) Put(token *models.Token) error {
s.s.Lock()
defer s.s.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), s.t)
defer cancel()
_, _, err := s.c.Collection(s.n).Add(ctx, token)
return err
}
func (s *store) Get(key string, val interface{}) (*models.Token, error) {
s.s.Lock()
defer s.s.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), s.t)
defer cancel()
iter := s.c.Collection(s.n).Where(key, "==", val).Limit(1).Documents(ctx)
doc, err := first(iter)
if err != nil {
return nil, err
}
info := &models.Token{}
err = doc.DataTo(info)
return info, err
}
func (s *store) Del(key string, val interface{}) error {
s.s.Lock()
defer s.s.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), s.t)
defer cancel()
return s.c.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
query := s.c.Collection(s.n).Where(key, "==", val).Limit(1)
iter := tx.Documents(query)
doc, err := first(iter)
if err != nil {
if err == iterator.Done || err == ErrDocumentDoesNotExist {
return nil // Document does not exist - we're done!
}
return err
}
return tx.Delete(doc.Ref)
})
}
// ErrDocumentDoesNotExist is returned whenever a Firestore document does not exist.
var ErrDocumentDoesNotExist = errors.New("document does not exist")
func first(iter *firestore.DocumentIterator) (*firestore.DocumentSnapshot, error) {
doc, err := iter.Next()
if err != nil {
return nil, err
}
if !doc.Exists() {
return nil, ErrDocumentDoesNotExist
}
return doc, nil
}