/
db.go
59 lines (45 loc) · 1.16 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
package db
import (
"context"
"strings"
"time"
"github.com/noona-hq/app-blacklist/logger"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Database struct {
cfg Config
logger logger.Logger
DB *mongo.Database
}
func New(cfg Config, logger logger.Logger) (*Database, error) {
d := &Database{
cfg: cfg,
logger: logger,
}
if err := d.connect(); err != nil {
return nil, err
}
return d, nil
}
func (d *Database) connect() error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
mongoOps := &options.ClientOptions{}
mongoOps.SetDirect(d.cfg.DirectConnection)
mongoOps.SetMaxPoolSize(200)
trimmedConnectionString := strings.TrimSuffix(d.cfg.Connection, "\n")
d.logger.Info("Connecting to database")
client, err := mongo.Connect(ctx, options.Client().ApplyURI(trimmedConnectionString), mongoOps)
if err != nil {
return err
}
// Ping the primary
if err := client.Ping(ctx, readpref.Primary()); err != nil {
return err
}
d.logger.Info("Database connected")
d.DB = client.Database(d.cfg.Name)
return nil
}