-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcommon.go
More file actions
77 lines (63 loc) · 1.61 KB
/
common.go
File metadata and controls
77 lines (63 loc) · 1.61 KB
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
package mongo
import (
"context"
"time"
log "github.com/sirupsen/logrus"
)
const (
DbName = "flyover"
)
type DbInteraction string
const (
Read DbInteraction = "READ"
Insert DbInteraction = "INSERT"
Update DbInteraction = "UPDATE"
Upsert DbInteraction = "UPSERT"
Delete DbInteraction = "DELETE"
)
func logDbInteraction(interaction DbInteraction, value any) {
const msgTemplate = "%s interaction with db: %+v"
switch interaction {
case Insert, Update, Upsert:
log.Infof(msgTemplate, interaction, value)
case Read:
log.Debugf(msgTemplate, interaction, value)
case Delete:
log.Debugf(msgTemplate, interaction, value)
default:
log.Debug("Unknown DB interaction")
}
}
type Connection struct {
client DbClientBinding
db DbBinding
timeout time.Duration
}
func NewConnection(client DbClientBinding, timeout time.Duration) *Connection {
db := client.Database(DbName)
return &Connection{client: client, db: db, timeout: timeout}
}
func (c *Connection) GetDb() DbBinding {
return c.db
}
func (c *Connection) Collection(collection string) CollectionBinding {
return c.db.Collection(collection)
}
func (c *Connection) Shutdown(closeChannel chan<- bool) {
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
err := c.client.Disconnect(ctx)
cancel()
closeChannel <- true
if err != nil {
log.Error("Error disconnecting from MongoDB: ", err)
} else {
log.Debug("Disconnected from MongoDB")
}
}
func (c *Connection) CheckConnection(ctx context.Context) bool {
err := c.client.Ping(ctx, nil)
if err != nil {
log.Error("Error checking database connection: ", err)
}
return err == nil
}