-
Notifications
You must be signed in to change notification settings - Fork 1
/
firestoreClient.go
87 lines (73 loc) · 1.83 KB
/
firestoreClient.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
package datastore
import (
"context"
"fmt"
"strings"
firebase "firebase.google.com/go"
"google.golang.org/api/option"
)
// FirestoreClient implements Client
type FirestoreClient struct {
app *firebase.App
}
func (fc *FirestoreClient) init() error {
opt := option.WithCredentialsFile("firebase-creds.json")
app, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
return err
}
fc.app = app
return nil
}
// GetKeywordPool gets the pool of keywords from the database
func (fc *FirestoreClient) GetKeywordPool() ([]string, error) {
var keywords []string
cl, err := fc.app.Firestore(context.Background())
if err != nil {
return nil, err
}
defer cl.Close()
snap, err := cl.Collection("api").Doc("keyword-pool").Get(context.Background())
if err != nil {
return nil, err
}
keywordSnap, err := snap.DataAt("keywords")
if err != nil {
return nil, err
}
for _, word := range keywordSnap.([]interface{}) {
keywords = append(keywords, strings.TrimSpace(word.(string)))
}
return keywords, nil
}
// AddNewsItems add a list of news items to the database
func (fc *FirestoreClient) AddNewsItems(newsItems []NewsItem) error {
cl, err := fc.app.Firestore(context.Background())
if err != nil {
return err
}
defer cl.Close()
ref := cl.Collection("api/result/tips")
for _, nItem := range newsItems {
ref.Add(context.Background(), nItem)
}
return nil
}
// CacheNewsTitle to the database
func (fc *FirestoreClient) CacheNewsTitle(titles []string) error {
cl, err := fc.app.Firestore(context.Background())
if err != nil {
return err
}
defer cl.Close()
ref := cl.Collection("api/title-cache/")
for _, title := range titles {
_, _, err := ref.Add(context.Background(), title)
if err != nil {
fmt.Println(err)
}
}
return nil
}
// func (fc *FirestoreClient) GetTitleCache() ([]string, error) {
// }