-
Notifications
You must be signed in to change notification settings - Fork 0
/
firebase.go
93 lines (75 loc) · 2.1 KB
/
firebase.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
88
89
90
91
92
93
package firebase
import (
"context"
"encoding/base64"
"fmt"
"cloud.google.com/go/firestore"
firebase "firebase.google.com/go"
"firebase.google.com/go/messaging"
"google.golang.org/api/option"
)
type Config struct {
ParentCollection string
ParentDocument string
SubParentCollection string
Collection string
DocName string
}
func GetDecodedFireBaseKey(key string) ([]byte, error) {
fireBaseAuthKey := key
decodedKey, err := base64.StdEncoding.DecodeString(fireBaseAuthKey)
if err != nil {
return nil, err
}
return decodedKey, nil
}
func Initialize(key string) (*firebase.App, error) {
decodedKey, err := GetDecodedFireBaseKey(key)
if err != nil {
return nil, err
}
opts := []option.ClientOption{option.WithCredentialsJSON(decodedKey)}
// Initialize firebase app
app, err := firebase.NewApp(context.Background(), nil, opts...)
if err != nil {
return nil, err
}
return app, nil
}
// Send Push notifications to a single device
func SendSingleNotification(key string, messaging *messaging.Message) error {
app, err := Initialize(key)
if err != nil {
return err
}
fcmClient, err := app.Messaging(context.Background())
if err != nil {
return err
}
_, err = fcmClient.Send(context.Background(), messaging)
if err != nil {
return err
}
return nil
}
func AddData(key string, data interface{}, cf Config) (*firestore.DocumentRef, error) {
app, err := Initialize(key)
if err != nil {
return nil, err
}
client, err := app.Firestore(context.Background())
if err != nil {
return nil, fmt.Errorf("error getting Firestore client: %v", err)
}
defer client.Close()
// Create a reference to the parent collection
parentDocRef := client.Collection(cf.ParentCollection).Doc(cf.ParentDocument)
// Create a reference to the new subcollection
subParentDocRef := parentDocRef.Collection(cf.SubParentCollection).Doc(cf.DocName)
// Create a new document in the subcollection
doc, _, err := subParentDocRef.Collection(cf.Collection).Add(context.Background(), data)
if err != nil {
return nil, fmt.Errorf("failed to create subdocument: %v", err)
}
return doc, err
}