/
firestore.go
79 lines (65 loc) · 1.66 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
76
77
78
79
package firestore
import (
"context"
"cloud.google.com/go/firestore"
firebase "firebase.google.com/go"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
)
type Firestore struct {
Client *firestore.Client
}
func New(credentialsFile string) (*Firestore, error) {
opt := option.WithCredentialsFile(credentialsFile)
app, errApp := firebase.NewApp(context.Background(), nil, opt)
if errApp != nil {
return nil, errApp
}
client, errFirestore := app.Firestore(context.Background())
if errFirestore != nil {
return nil, errFirestore
}
return &Firestore{
Client: client,
}, nil
}
func (f *Firestore) GetData(collection string) (map[string]map[string]interface{}, error) {
iter := f.Client.Collection(collection).Documents(context.Background())
result := map[string]map[string]interface{}{}
for {
doc, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
id := doc.Ref.ID
data := doc.Data()
iterSubCollections := doc.Ref.Collections(context.Background())
for {
collectionRef, err := iterSubCollections.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
iterSubCollectionsData := f.Client.Collection(collection).Doc(doc.Ref.ID).Collection(collectionRef.ID).Documents(context.Background())
subCollections := map[string]interface{}{}
for {
dataSnapshot, err := iterSubCollectionsData.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
subCollections[dataSnapshot.Ref.ID] = dataSnapshot.Data()
data[collectionRef.ID] = subCollections
}
}
result[id] = data
}
return result, nil
}