-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
80 lines (60 loc) · 1.56 KB
/
util.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
package metisoft_go_firebase_util
import (
"fmt"
"golang.org/x/net/context"
firebase "firebase.google.com/go"
"firebase.google.com/go/messaging"
"google.golang.org/api/option"
)
type ConfigurationOptions struct {
PathToServiceAccountKey string
DatabaseUrl string
FnGetFirebaseTokenForUser func(string) (string, error)
}
var configOptions ConfigurationOptions
var app *firebase.App
func defaultFnGetFirebaseTokenForUser(userId string) (token string, _ error) {
return userId, nil
}
func SendPushNotification(userId string, title string, body string) error {
token, err := configOptions.FnGetFirebaseTokenForUser(userId)
if err != nil {
return err
}
ctx := context.Background()
client, err := app.Messaging(ctx)
if err != nil {
return err
}
message := &messaging.Message{
Notification: &messaging.Notification{
Title: title,
Body: body,
},
Token: token,
}
_, err = client.Send(ctx, message)
if err != nil {
return err
}
return nil
}
func Init(options ConfigurationOptions) error {
var err error
if options.PathToServiceAccountKey == "" {
return fmt.Errorf("PathToServiceAccountKey in options is required")
}
if options.DatabaseUrl == "" {
return fmt.Errorf("DatabaseUrl in options is required")
}
if options.FnGetFirebaseTokenForUser == nil {
options.FnGetFirebaseTokenForUser = defaultFnGetFirebaseTokenForUser
}
configOptions = options
opt := option.WithCredentialsFile(options.PathToServiceAccountKey)
app, err = firebase.NewApp(context.Background(), nil, opt)
if err != nil {
return err
}
return nil
}