-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirestore-repo.go
85 lines (69 loc) · 1.78 KB
/
firestore-repo.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
package repositorty
import (
"context"
"fmt"
"log"
firebase "firebase.google.com/go"
"github.com/kuma-coffee/go-crash-course/unit-testing-code-by-mocking-with-testify/entity"
"google.golang.org/api/option"
)
type repo struct {
}
// New Firestore Repository
func NewFirestoreRepository() PostRepository {
return &repo{}
}
const (
collectionName string = "posts"
)
func (*repo) Save(post *entity.Post) (*entity.Post, error) {
ctx := context.Background()
opt := option.WithCredentialsFile("../pragmatic-reviews.json")
app, err := firebase.NewApp(ctx, nil, opt)
if err != nil {
return nil, fmt.Errorf("error initializing app: %v", err)
}
client, err := app.Firestore(ctx)
if err != nil {
return nil, fmt.Errorf("error initializing firestore: %v", err)
}
defer client.Close()
_, _, err = client.Collection(collectionName).Add(ctx, map[string]interface{}{
"ID": post.ID,
"Title": post.Title,
"Text": post.Text,
})
if err != nil {
log.Fatalf("Failed adding a new post: %v", err)
return nil, err
}
return post, nil
}
func (*repo) FindAll() ([]entity.Post, error) {
ctx := context.Background()
opt := option.WithCredentialsFile("../pragmatic-reviews.json")
app, err := firebase.NewApp(ctx, nil, opt)
if err != nil {
return nil, fmt.Errorf("error initializing app: %v", err)
}
client, err := app.Firestore(ctx)
if err != nil {
return nil, fmt.Errorf("error initializing firestore: %v", err)
}
defer client.Close()
var posts []entity.Post
iterator := client.Collection(collectionName).Documents(ctx)
for {
doc, err := iterator.Next()
if err != nil {
break
}
post := entity.Post{
ID: doc.Data()["ID"].(int64),
Title: doc.Data()["Title"].(string),
Text: doc.Data()["Text"].(string),
}
posts = append(posts, post)
}
return posts, nil
}