package dbAccess import ( "git.fjla.uk/owlboard/timetable-mgr/helpers" "git.fjla.uk/owlboard/timetable-mgr/log" "context" "fmt" "time" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) // Provide the DB Connection to other functions var MongoClient (*mongo.Client) // Builds the DB URI based on the loaded configuration parameters func getDbUri(cfg *helpers.Configuration) string { var uri = "mongodb://" + cfg.DbUser + ":" + cfg.DbPass + "@" + cfg.DbHost + ":" + cfg.DbPort return uri } // Configure bsonOpts var bsonOpts = &options.BSONOptions{ UseJSONStructTags: true, } // Initialise the DB Connection func InitDataAccess(cfg *helpers.Configuration) { uri := getDbUri(cfg) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri).SetBSONOptions(bsonOpts)) if err != nil { fmt.Println(err) log.Msg.Fatal("Error connecting to database: " + err.Error()) } else { log.Msg.Info("Database connection successful") } MongoClient = client } // Closes the connection to the database - used for cleanup functions 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.") } } }