mirror-nourybot/pkg/db/connect.go

45 lines
851 B
Go
Raw Normal View History

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 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
}