@@ -3,39 +3,46 @@ package database
33import (
44 "context"
55 "fmt"
6- "os"
76 "time"
87
98 "go.mongodb.org/mongo-driver/mongo"
109 "go.mongodb.org/mongo-driver/mongo/options"
1110 "go.mongodb.org/mongo-driver/mongo/readpref"
1211)
1312
14- func (c * DBQueryClient ) Connect () error {
15- uri := os .Getenv ("MONGO_URI" )
13+ type MongoConnection struct {
14+ db * mongo.Client
15+ }
16+
17+ func NewMongoConnection (params * DBConnectionParams ) (* MongoConnection , error ) {
18+ uri := params .URI
1619 ctx , cancel := context .WithTimeout (context .Background (), 10 * time .Second )
1720 defer cancel ()
1821
1922 client , err := mongo .Connect (ctx , options .Client ().ApplyURI (uri ))
2023 if err != nil {
21- fmt .Println ("Failed to connect to db" )
24+ fmt .Printf ("Failed to connect to db: %v \n " , err )
25+ return nil , err
2226 }
2327
2428 // Ping the primary
2529 if err := client .Ping (ctx , readpref .Primary ()); err != nil {
26- fmt . Println ( "Failed to ping after connecting to the db" )
30+ return nil , err
2731 }
2832 fmt .Println ("Successfully connected and pinged." )
2933
30- c .Client = client
31- return err
34+ return & MongoConnection {db : client }, nil
35+ }
36+
37+ func (c * MongoConnection ) GetDB () * mongo.Client {
38+ return c .db
3239}
3340
34- func (c * DBQueryClient ) GetDB () * mongo.Client {
35- err := c . Connect ( )
41+ func (c * DBQueryClient ) Connect ( params * DBConnectionParams ) ( * mongo.Client , error ) {
42+ conn , err := NewMongoConnection ( params )
3643 if err != nil {
37- panic ( err )
44+ return nil , err
3845 }
3946
40- return c . Client
47+ return conn . GetDB (), nil
4148}
0 commit comments