-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirestore.go
75 lines (61 loc) · 1.61 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
package storage
import (
"context"
"encoding/json"
"log"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"cloud.google.com/go/firestore"
"github.com/momocomics/backend/grpc-server/pkg/pb"
)
type Firestore struct {
collection string
client *firestore.Client
}
func NewFirestore(ctx context.Context, credentialsFile, projectId, collection string) (*Firestore, error) {
log.Printf("Initializing Firestore with collection %q in projet %q", collection, projectId)
var client *firestore.Client
var err error
if credentialsFile == "" {
client, err = firestore.NewClient(ctx, projectId)
} else {
client, err = firestore.NewClient(ctx, projectId, option.WithCredentialsFile(credentialsFile))
}
if err != nil {
return nil, err
}
return &Firestore{client: client, collection: collection}, nil
}
func (fs *Firestore) Add(ctx context.Context, t *pb.Task) error {
_, err := fs.client.Collection(fs.collection).Doc(t.Id).Set(ctx, t)
if err != nil {
return err
}
return nil
}
func (fs *Firestore) List(ctx context.Context, category *pb.Category) ([]*pb.Task, error) {
ti := fs.client.Collection(fs.collection).Where("Category.Name", "==", category.Name).Documents(ctx)
var tasks []*pb.Task
for {
doc, err := ti.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
jb, err := json.Marshal(doc.Data())
if err != nil {
return nil, err
}
var task pb.Task
if err := json.Unmarshal(jb, &task); err != nil {
return nil, err
}
tasks = append(tasks, &task)
}
return tasks, nil
}
func (fs *Firestore) Close() error {
return fs.client.Close()
}