/
firestore.go
71 lines (60 loc) · 1.59 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
package whitelist
import (
"context"
"strconv"
"cloud.google.com/go/firestore"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
// FirestoreService ...
type FirestoreService struct {
client *firestore.Client
}
// NewFirestoreService ...
func NewFirestoreService(client *firestore.Client) *FirestoreService {
return &FirestoreService{client}
}
// IsIn ...
func (s *FirestoreService) IsIn(id int64) (bool, error) {
_, err := s.client.Collection("whitelist").Doc(strconv.Itoa(int(id))).Get(context.Background())
switch grpc.Code(err) {
case codes.OK:
// do nothing
case codes.NotFound:
return false, nil
default:
return false, errors.Wrapf(err, "not able to Get doc ID: %d", id)
}
return true, nil
}
// CreateIfNotExists ...
func (s *FirestoreService) CreateIfNotExists(id int64, username string) error {
snap, err := s.client.Collection("whitelist").Doc(strconv.Itoa(int(id))).Get(context.Background())
switch grpc.Code(err) {
case codes.OK:
if snap.Exists() {
return nil
}
case codes.NotFound:
// proceed do create
default:
return errors.Wrapf(err, "not able to get %s: %d", username, id)
}
_, err = snap.Ref.Create(context.Background(), map[string]interface{}{
"id": id,
"username": username,
})
if err != nil {
return errors.Wrap(err, "snap.Ref.Create")
}
return nil
}
// Delete ...
func (s *FirestoreService) Delete(id int64) error {
_, err := s.client.Collection("whitelist").Doc(strconv.Itoa(int(id))).Delete(context.Background())
if err != nil {
return errors.Wrapf(err, "not able to delete: %d", id)
}
return nil
}