Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 31 additions & 20 deletions uploader/database.go
Original file line number Diff line number Diff line change
@@ -1,45 +1,56 @@
/*
This file is responsible for providing various useful database functions.
This file is responsible for providing various useful database functions.
*/

package uploader

import (
//"go.mongodb.org/mongo-driver/bson"
//"go.mongodb.org/mongo-driver/bson/primitive"
"context"
"log"
"os"
"sync"
"time"

"github.com/UTDNebula/api-tools/utils"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

// TODO: Replace instances and check
type DBSingleton struct {
client *mongo.Client
}

var dbInstance *DBSingleton
var once sync.Once

func connectDB() *mongo.Client {
once.Do(func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
opts := options.Client().ApplyURI(getEnvMongoURI())

opts := options.Client().ApplyURI(getEnvMongoURI())
client, err := mongo.Connect(ctx, opts)
if err != nil {
log.Panic("Unable to create MongoDB client and connect to database")
os.Exit(1)
}

client, err := mongo.Connect(ctx, opts)
if err != nil {
log.Panic("Unable to create MongoDB client and connect to database")
os.Exit(1)
}
// ping the database
err = client.Ping(ctx, nil)
if err != nil {
log.Panic("Unable to ping database")
os.Exit(1)
}

//ping the database
err = client.Ping(ctx, nil)
if err != nil {
log.Panic("Unable to ping database")
os.Exit(1)
}
log.Println("Connected to MongoDB")

log.Println("Connected to MongoDB")
dbInstance = &DBSingleton{
client: client,
}
})

return client
return dbInstance.client
}

func getCollection(client *mongo.Client, collectionName string) *mongo.Collection {
Expand Down