Newer
Older
package database
import (
"context"
"log"
"time"
"code.fbi.h-da.de/danet/gosdn/controller/config"
"code.fbi.h-da.de/danet/gosdn/controller/store"
"github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
// Timeout operations after N seconds.
// DatabaseName is the name of the mongoDB database used.
DatabaseName = "gosdn"
)
// Connect Retrieves a client to the MongoDB.
func Connect() (*mongo.Database, error) {
mongoConnection := config.DatabaseConnection
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoConnection))
if err != nil {
log.Printf("Failed to create client: %v", err)
}
// Force a connection to verify our connection string
err = client.Ping(ctx, nil)
if err != nil {
log.Printf("Failed to connect to database: %v\n", err)
}
db := client.Database(DatabaseName)
if db == nil {
return nil, fmt.Errorf("can not connect to database %s", DatabaseName)
}
return db, nil
}
func GetDatabaseConnection() *mongo.Database {
var db *mongo.Database
storeMode := store.GetStoreMode()
if storeMode == store.Database {
db, err := Connect()
if err != nil {
logrus.Infof("Could not connect to database")
}
return db
}
return db