2023-02-11 16:00:16 +00:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"os"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo/readpref"
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
var client *mongo.Client
|
|
|
|
|
|
|
|
func DB() {
|
2023-03-10 20:59:56 +00:00
|
|
|
Log("Connecting to the database...")
|
2023-02-11 16:00:16 +00:00
|
|
|
|
2023-03-12 18:17:28 +00:00
|
|
|
uri := MainConfig.MongoDB + "/?retryWrites=true&w=majority"
|
2023-02-11 16:00:16 +00:00
|
|
|
|
|
|
|
var err error
|
|
|
|
|
|
|
|
client, err = mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
|
|
|
|
if err != nil {
|
2023-03-10 20:59:56 +00:00
|
|
|
Fatal("DB", err)
|
2023-02-11 16:00:16 +00:00
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Ping the primary
|
|
|
|
if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {
|
2023-03-10 20:59:56 +00:00
|
|
|
Fatal("DB", err)
|
2023-02-11 16:00:16 +00:00
|
|
|
}
|
|
|
|
|
2023-03-10 20:59:56 +00:00
|
|
|
Log("Successfully connected to the database.")
|
2023-02-11 16:00:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func Disconnect() {
|
|
|
|
if err := client.Disconnect(context.TODO()); err != nil {
|
2023-03-10 20:59:56 +00:00
|
|
|
Fatal("DB", err)
|
2023-02-11 16:00:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetCollection(applicationId string, collection string) *mongo.Collection {
|
2023-03-10 20:59:56 +00:00
|
|
|
if client == nil {
|
|
|
|
DB()
|
|
|
|
}
|
|
|
|
|
2023-02-11 16:00:16 +00:00
|
|
|
name := os.Getenv("MONGODB_NAME"); if name == "" {
|
2023-03-10 20:59:56 +00:00
|
|
|
name = "COSMOS"
|
2023-02-11 16:00:16 +00:00
|
|
|
}
|
2023-03-10 20:59:56 +00:00
|
|
|
|
|
|
|
Debug("Getting collection " + applicationId + "_" + collection + " from database " + name)
|
|
|
|
|
2023-02-11 16:00:16 +00:00
|
|
|
c := client.Database(name).Collection(applicationId + "_" + collection)
|
2023-03-10 20:59:56 +00:00
|
|
|
|
2023-02-11 16:00:16 +00:00
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
|
|
|
// func query(q string) (*sql.Rows, error) {
|
|
|
|
// return db.Query(q)
|
|
|
|
// }
|