/
mongo.go
69 lines (53 loc) · 1.29 KB
/
mongo.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
package mongo
import (
"context"
"net/url"
"strings"
"time"
"github.com/frain-dev/migrate-to-postgres/convoy082/config"
"github.com/newrelic/go-agent/v3/integrations/nrmongo"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Client struct {
db *mongo.Database
}
func New(cfg config.Configuration) (*Client, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
opts := options.Client()
newRelicMonitor := nrmongo.NewCommandMonitor(nil)
opts.SetMonitor(newRelicMonitor)
opts.ApplyURI(cfg.Database.Dsn)
client, err := mongo.Connect(ctx, opts)
if err != nil {
return nil, err
}
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := client.Ping(ctx, nil); err != nil {
return nil, err
}
u, err := url.Parse(cfg.Database.Dsn)
if err != nil {
return nil, err
}
dbName := strings.TrimPrefix(u.Path, "/")
conn := client.Database(dbName, nil)
c := &Client{
db: conn,
}
return c, nil
}
func (c *Client) Disconnect(ctx context.Context) error {
return c.db.Client().Disconnect(ctx)
}
func (c *Client) GetName() string {
return "mongo"
}
func (c *Client) Client() interface{} {
return c.db
}
func (c *Client) Database() *mongo.Database {
return c.db
}