-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
83 lines (70 loc) · 2.38 KB
/
db.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
package database
import (
"context"
"errors"
"fmt"
"os"
"github.com/rs/zerolog"
"github.com/umee-network/umeed-indexer/database/firebase"
"github.com/umee-network/umeed-indexer/graph/types"
)
// TypeDB defines the databases available for indexing.
type TypeDB uint8
const (
// Firebase is the default DB for this indexer.
Firebase TypeDB = iota + 1
// TODO: add in memory for testing.
)
// Database defines the exported functions of the database.
type Database interface {
/*
Basic
*/
// Close closes the needed connections.
Close() error
// DeleteAll inside the database.
DeleteAll(ctx context.Context) error
/*
Chain Data
*/
// DeleteChainData delete the chain data and all of its structures inside.
DeleteChainData(ctx context.Context, chainID string) error
// UpsertChainInfo updates or inserts a chain info structure.
UpsertChainInfo(ctx context.Context, info types.ChainInfo) (err error)
// GetChainInfo returns the last chainInfo.
GetChainInfo(ctx context.Context, chainID string) (info *types.ChainInfo, err error)
// StoreMsgLiquidate stores a new msgliquidate updating the CosmosMsgIndexed.
StoreMsgLiquidate(ctx context.Context, chainID string, txHash []byte, blockHeight int, msg types.MsgLiquidate) error
}
// NewDB returns a new database instance based on the specified type.
// It returns an error if the database type is unsupported.
func NewDB(typeDB TypeDB, ctx context.Context, logger zerolog.Logger) (Database, error) {
switch typeDB {
case Firebase:
return loadFirebase(ctx, logger)
default:
return nil, fmt.Errorf("unsupported database type: %v", typeDB)
}
}
// loadFirebase checks if there is env set for emulator, if it is loads firebase without credentials
// otherwise it looks for credentials to run
func loadFirebase(ctx context.Context, logger zerolog.Logger) (Database, error) {
firebaseEmulator := os.Getenv(firebase.EnvFirebaseEmulator)
if len(firebaseEmulator) > 0 {
fmt.Printf(
"\nEnv %s detected as %s, API running on firestore emulator",
firebase.EnvFirebaseEmulator,
firebaseEmulator,
)
return firebase.New(ctx, logger)
}
opt, err := firebase.LoadCredential()
if err != nil {
return nil, errors.Join(err, errors.New("Failed to load Firebase credentials"))
}
db, err := firebase.New(ctx, logger, opt)
if err != nil {
return nil, errors.Join(err, errors.New("failed to initialize Firebase database"))
}
return db, err
}