mongo procedure

This commit is contained in:
mr 2024-08-01 11:31:50 +02:00
parent dbbda34117
commit 69d53f9d4d

View File

@ -16,11 +16,11 @@ import (
)
var (
mngoClient *mongo.Client
mngoDB *mongo.Database
MngoCtx context.Context
cancel context.CancelFunc
mngoClient *mongo.Client
mngoDB *mongo.Database
MngoCtx context.Context
cancel context.CancelFunc
isConnected bool
existingCollections []string
mngoCollections []string
mngoConfig MongoConf
@ -40,29 +40,16 @@ type MongoDB struct {
func (m *MongoDB) Init(collections []string, config MongoConf) {
// var baseConfig string
isConnected = false
m.Logger = logs.GetLogger()
ResourceMap = make(map[string]interface{})
m.Logger.Info().Msg("Connecting to" + config.GetUrl())
mngoCollections = collections
mngoConfig = config
if err := m.createClient(config.GetUrl()); err == nil {
m.connect()
}
err := m.createClient(config.GetUrl())
m.Logger.Error().Msg(err.Error())
}
func (m *MongoDB) connect() error {
if mngoClient == nil {
m.Logger.Info().Msg("Connecting mongo client to db " + mngoConfig.GetDatabase())
m.prepareDB(mngoCollections, mngoConfig)
m.Logger.Info().Msg("Database is READY")
return nil
} else {
return m.createClient(mngoConfig.GetUrl())
}
}
func (m *MongoDB) createClient(MongoURL string) error {
var err error
// Allows us to use marshal and unmarshall with results of FindOne() and others
@ -77,19 +64,27 @@ func (m *MongoDB) createClient(MongoURL string) error {
mngoClient, err = mongo.Connect(MngoCtx, clientOptions)
if err != nil {
mngoClient = nil
isConnected = false
return errors.New("Mongodb NewClient " + MongoURL + ":" + err.Error())
}
// Ping the primary
if mngoClient, err = mongo.Connect(MngoCtx, clientOptions); err != nil {
mngoClient = nil
isConnected = false
return errors.New("Mongodb connect " + MongoURL + ":" + err.Error())
}
if err = mngoClient.Ping(MngoCtx, nil); err != nil {
mngoClient = nil
isConnected = false
return errors.New("Mongodb ping " + MongoURL + ":" + err.Error())
}
if !isConnected {
m.Logger.Info().Msg("Connecting mongo client to db " + mngoConfig.GetDatabase())
m.prepareDB(mngoCollections, mngoConfig)
m.Logger.Info().Msg("Database is READY")
}
return nil
}
@ -114,6 +109,7 @@ func (m *MongoDB) prepareDB(list_collection []string, config MongoConf) {
CollectionMap[collection_name] = new_collection
}
}
isConnected = true
}
// Creates the collection with index specified in mongo/mongo_collections