69 lines
1.6 KiB
Go

package dbAccess
import (
"git.fjla.uk/owlboard/mq-client/log"
"context"
"fmt"
"os"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
// "go.mongodb.org/mongo-driver/mongo/readpref"
)
// Generate DB Url
var dbUri string = getDbUri()
func getDbUri() string {
log.Msg.Debug("Fetching DB Access details")
var dbHost string = os.Getenv("OWL_DB_HOST")
if dbHost == "" {
dbHost = "localhost"
}
var dbPort string = os.Getenv("OWL_DB_PORT")
if dbPort == "" {
dbPort = "27017"
}
var dbUser string = os.Getenv("OWL_DB_USER")
if dbUser == "" {
dbUser = "owl"
}
var dbPass string = os.Getenv("OWL_DB_PASS")
if dbPass == "" {
dbPass = "twittwoo"
}
var uri = "mongodb://" + dbUser + ":" + dbPass + "@" + dbHost + ":" + dbPort
return uri
}
// Provide the DB Connection to other functions
var MongoClient (*mongo.Client) = initDataAccess()
// Initialise the DB Connection
func initDataAccess() *mongo.Client {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(dbUri))
if err != nil {
fmt.Println(err)
log.Msg.Fatal("Error connecting to database: " + err.Error())
} else {
log.Msg.Info("Database connection successful")
}
return client
}
func CloseMongoClient() {
if MongoClient != nil {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := MongoClient.Disconnect(ctx); err != nil {
log.Msg.Warn("Error disconnecting MongoDB client: " + err.Error())
} else {
log.Msg.Info("MongoDB client disconnected.")
}
}
}