oc-lib/mongo.go

127 lines
2.8 KiB
Go
Raw Normal View History

2024-07-16 10:56:36 +02:00
package oclib
import (
"context"
"encoding/json"
"errors"
"os"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/x/bsonx"
)
var (
mngoClient *mongo.Client
mngoDB *mongo.Database
MngoCtx context.Context
)
// Trying to get vscode to display this
func MongoInit() {
// var baseConfig string
var err error
var cancel context.CancelFunc
var conf map[string]string
var MongoURL string
var DBname string
db_conf, err := os.ReadFile("oclib_conf.json")
if err != nil {
logger.Fatal().Msg("Could not find configuration file")
}
json.Unmarshal(db_conf,&conf)
if len(os.Getenv("DOCKER_ENVIRONMENT")) == 0 {
MongoURL = conf["DB_URL_LOCAL"]
} else {
MongoURL = conf["DB_URL_DOCKER"]
}
DBname = conf["DCNAME"] + "-" + conf["DBPOINT"]
logger.Info().Msg("Connecting to" + MongoURL)
MngoCtx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
createClient(MongoURL)
logger.Info().Msg("Connecting mongo client to db " + DBname)
prepareDB(conf["DCNAME"],conf["DBPOINT"])
logger.Info().Msg("Database is READY")
}
// TODO : Soit retourner MngoCtx, soit comprendre comment passer sa référence et la mettre à jour
func createClient(MongoURL string){
var err error
clientOptions := options.Client().ApplyURI(MongoURL)
mngoClient, _ = mongo.NewClient(options.Client().ApplyURI(MongoURL))
if err = mngoClient.Connect(MngoCtx); err != nil {
logger.Fatal().Msg("Mongodb NewClient " + MongoURL + ":" + "err" )
panic(err)
}
// Ping the primary
if mngoClient, err = mongo.Connect(MngoCtx, clientOptions); err != nil {
logger.Fatal().Msg("Mongodb connect " + MongoURL + ":" + "err" )
panic(err)
}
if err = mngoClient.Ping(MngoCtx, nil); err != nil {
logger.Fatal().Msg("Mongodb ping " + MongoURL + ":" + "err" )
panic(err)
}
}
func prepareDB(dc_name string, db_point string) {
// var err error
DBname := dc_name + "-" + db_point
mngoDB = mngoClient.Database(DBname)
list_collection := [...]string{"Data","Computing","Storage","Datacenter","Workspace","Schedule"}
for _, collection_name := range(list_collection){
new_collection := mngoDB.Collection(collection_name)
createCollection(new_collection)
}
}
func createCollection(new_collection *mongo.Collection) {
var err error
if _, err = new_collection.Indexes().CreateMany(MngoCtx, []mongo.IndexModel{
{
Keys: bsonx.Doc{
{Key: "description", Value: bsonx.String("text")},
{Key: "example", Value: bsonx.String("text")},
},
},
}); err != nil {
var cmdErr mongo.CommandError
if errors.As(err, &cmdErr) && cmdErr.Code != 85 {
logger.Fatal().Msg("It failed but I saw it: " + err.Error())
panic(err)
} else if !errors.As(err, &cmdErr) {
logger.Fatal().Msg("Unexpected error: " + err.Error())
panic(err)
}
}
}