2021-10-25 23:33:00 +02:00
|
|
|
package db
|
|
|
|
|
2021-10-27 15:39:21 +02:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/lyx0/nourybot/pkg/config"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
|
|
)
|
|
|
|
|
2021-10-28 21:49:54 +02:00
|
|
|
// Connect connects the the MongoDB database through a supplied cfg
|
|
|
|
// and returns a *mongo.Client
|
2021-10-28 17:48:18 +02:00
|
|
|
func Connect(cfg *config.Config) *mongo.Client {
|
|
|
|
client, err := mongo.NewClient(options.Client().ApplyURI(cfg.MongoURI))
|
2021-10-27 15:39:21 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2021-10-28 15:22:19 +02:00
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
2021-10-27 15:39:21 +02:00
|
|
|
err = client.Connect(ctx)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2021-10-27 19:27:35 +02:00
|
|
|
// defer client.Disconnect(ctx)
|
2021-10-27 15:39:21 +02:00
|
|
|
|
2021-10-28 16:16:11 +02:00
|
|
|
err = client.Ping(context.TODO(), nil)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Info("Connected to MongoDB!")
|
|
|
|
|
2021-10-27 15:39:21 +02:00
|
|
|
databases, err := client.ListDatabaseNames(ctx, bson.M{})
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2021-10-28 16:16:11 +02:00
|
|
|
_ = databases
|
|
|
|
// log.Info(databases)
|
2021-10-27 15:39:21 +02:00
|
|
|
|
|
|
|
return client
|
|
|
|
}
|