-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirebase.go
85 lines (70 loc) · 1.88 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
package mallard
import (
"cloud.google.com/go/firestore"
"context"
"errors"
firebase "firebase.google.com/go/v4"
"firebase.google.com/go/v4/auth"
"google.golang.org/api/option"
"log"
"os"
"strings"
)
type FirebaseServiceType int
const (
Authentication FirebaseServiceType = iota
Firestore
)
type ServiceBundle struct {
App *firebase.App
Authentication *auth.Client
Firestore *firestore.Client
}
var ErrorAlreadyInitialized = errors.New("service is already initialized")
var ErrorUnsupportedService = errors.New("unsupported service")
func GetFirebase(ctx context.Context, services ...FirebaseServiceType) (*ServiceBundle, error) {
bundle := &ServiceBundle{}
var err error
bundle.App, err = getApp()
if err != nil {
return nil, err
}
for _, service := range services {
switch service {
case Authentication:
if bundle.Authentication != nil {
return nil, ErrorAlreadyInitialized
}
bundle.Authentication, err = bundle.App.Auth(ctx)
if err != nil {
return nil, ErrorAlreadyInitialized
}
case Firestore:
if bundle.Firestore != nil {
return nil, ErrorAlreadyInitialized
}
bundle.Firestore, err = bundle.App.Firestore(ctx)
if err != nil {
return nil, ErrorAlreadyInitialized
}
default:
return nil, ErrorUnsupportedService
}
}
return bundle, nil
}
func getApp() (*firebase.App, error) {
ctx := context.Background()
env := strings.ToUpper(os.Getenv("MITS_ENV"))
log.Printf("Initializing Firebase in environment %s\n", env)
if env == "DEV" {
serviceAccountJSONLocation := os.Getenv("MITS_SERVICE_ACCOUNT")
if serviceAccountJSONLocation == "" {
serviceAccountJSONLocation = "./service_account.json"
}
log.Printf("Using service account %s\n", serviceAccountJSONLocation)
opt := option.WithCredentialsFile(serviceAccountJSONLocation)
return firebase.NewApp(ctx, nil, opt)
}
return firebase.NewApp(ctx, nil)
}