common/mongo/connection.go

52 lines
1.1 KiB
Go
Raw Permalink Normal View History

2024-02-02 12:02:44 +00:00
package mongo
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type ConnectDeps struct {
Configuration *Configuration
Timeout time.Duration
}
func Connect(ctx context.Context, deps *ConnectDeps) (*mongo.Database, error) {
if deps == nil {
return nil, ErrEmptyArgs
}
connectionOptions := options.Client().
2024-12-13 12:21:18 +00:00
ApplyURI(deps.Configuration.URL)
2024-02-02 12:02:44 +00:00
ticker := time.NewTicker(1 * time.Second)
timeoutExceeded := time.After(deps.Timeout)
defer ticker.Stop()
for {
select {
case <-ticker.C:
connection, err := mongo.Connect(ctx, connectionOptions)
if err == nil {
err = connection.Ping(ctx, nil)
if err == nil {
return connection.Database(deps.Configuration.DatabaseName), nil
}
2024-11-28 14:49:32 +00:00
log.Printf("failed to ping the database <%s>: %s", deps.Configuration.URL, err.Error())
2024-02-02 12:02:44 +00:00
}
2024-11-28 14:49:32 +00:00
log.Printf("failed to connect to db <%s>: %s", deps.Configuration.URL, err.Error())
2024-02-02 12:02:44 +00:00
case <-timeoutExceeded:
2024-11-28 14:49:32 +00:00
return nil, fmt.Errorf("db connection <%s> failed after %d timeout", deps.Configuration.URL, deps.Timeout)
2024-02-02 12:02:44 +00:00
default:
time.Sleep(1 * time.Second)
}
}
}