50 lines
1.2 KiB
Go
50 lines
1.2 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
|
|
"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"
|
|
)
|
|
|
|
var dbClient *mongo.Client
|
|
var MongoDatabase *mongo.Database
|
|
|
|
func Connect() {
|
|
cmdMonitor := &event.CommandMonitor{
|
|
Started: func(_ context.Context, evt *event.CommandStartedEvent) {
|
|
// TODO: Log
|
|
},
|
|
}
|
|
|
|
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(viper.GetString("mongo.uri")).SetMonitor(cmdMonitor))
|
|
if err != nil {
|
|
// TODO: Log
|
|
panic(err)
|
|
}
|
|
|
|
err = client.Ping(context.TODO(), readpref.Nearest())
|
|
if err != nil {
|
|
// TODO: Log
|
|
panic(err)
|
|
}
|
|
|
|
dbClient = client
|
|
|
|
MongoDatabase = 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 Disconnect() {
|
|
err := dbClient.Disconnect(context.TODO())
|
|
if err != nil {
|
|
// TODO: Log
|
|
panic(err)
|
|
}
|
|
}
|