47 lines
1019 B
Go
47 lines
1019 B
Go
package mongo
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
serverconfig "krakatoa.net/backend/modules/configs/serverConfig"
|
|
"krakatoa.net/backend/modules/logger"
|
|
)
|
|
|
|
var MongoClient *mongo.Client
|
|
|
|
var PlayersCollection *mongo.Collection
|
|
|
|
func getConnectionURI() string {
|
|
cfg := serverconfig.Cfg.MongoDB
|
|
|
|
return "mongodb://" + cfg.Username + ":" + cfg.Password + "@" + cfg.Hostname + ":" + cfg.Port + "/?maxPoolSize=20&w=majority&authSource=" + cfg.Database
|
|
}
|
|
|
|
func InitDatabase() {
|
|
var err error
|
|
|
|
MongoClient, err = mongo.NewClient(options.Client().ApplyURI(getConnectionURI()))
|
|
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
err = MongoClient.Connect(ctx)
|
|
|
|
if err != nil {
|
|
logger.Mongo.Fatal(err)
|
|
}
|
|
|
|
db := MongoClient.Database(serverconfig.Cfg.MongoDB.Database)
|
|
|
|
PlayersCollection = db.Collection("players")
|
|
|
|
logger.Mongo.Info("Connected")
|
|
}
|