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" ) const databaseName string = "owlboard" const CorpusCollection string = "corpus" const StationsCollection string = "stations" const metaCollection string = "meta" const cifMetaCollection string = "cifMeta" const TimetableCollection string = "timetable" // Provide the DB Connection to other functions var MongoClient (*mongo.Client) 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 } 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.") } } }