55 lines
1.6 KiB
Go
55 lines
1.6 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
|
|
"git.1in9.net/raider/wroofauth/internal/logger"
|
|
"github.com/spf13/viper"
|
|
"go.mongodb.org/mongo-driver/event"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
"go.mongodb.org/mongo-driver/mongo/readpref"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
var dbClient *mongo.Client
|
|
var Mongo *mongo.Database
|
|
|
|
func MongoConnect(ctx context.Context) {
|
|
logger.Logger.Info("establishing connection to mongoDB...")
|
|
|
|
cmdMonitor := &event.CommandMonitor{
|
|
Started: func(_ context.Context, evt *event.CommandStartedEvent) {
|
|
logger.Logger.Debug("mongoDB command running", zap.String("command", evt.Command.String()))
|
|
},
|
|
}
|
|
|
|
client, err := mongo.Connect(ctx, options.Client().ApplyURI(viper.GetString("mongo.uri")).SetMonitor(cmdMonitor))
|
|
if err != nil {
|
|
logger.Logger.Fatal("unable to connect to MongoDB", zap.Error(err))
|
|
}
|
|
|
|
err = client.Ping(ctx, readpref.Nearest())
|
|
if err != nil {
|
|
logger.Logger.Fatal("unable to ping to MongoDB", zap.Error(err))
|
|
}
|
|
|
|
logger.Logger.Info("mongoDB connection established")
|
|
|
|
dbClient = client
|
|
|
|
Mongo = client.Database(viper.GetString("mongo.database"))
|
|
|
|
//UserCollection = Database.Collection(viper.GetString("mongo.collection.users"))
|
|
//ClientCollection = Database.Collection(viper.GetString("mongo.collection.clients"))
|
|
//GroupCollection = Database.Collection(viper.GetString("mongo.collection.groups"))
|
|
}
|
|
|
|
func MongoDisconnect(ctx context.Context) {
|
|
err := dbClient.Disconnect(ctx)
|
|
if err != nil {
|
|
logger.Logger.Warn("failed to gracefully disconnect MongoDB", zap.Error(err))
|
|
}
|
|
|
|
logger.Logger.Info("mongoDB gracefully disconnected")
|
|
}
|