-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathdatabase.go
More file actions
67 lines (54 loc) · 1.28 KB
/
database.go
File metadata and controls
67 lines (54 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
This file is responsible for providing various useful database functions.
*/
package uploader
import (
"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()
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)
}
// 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")
dbInstance = &DBSingleton{
client: client,
}
})
return dbInstance.client
}
func getCollection(client *mongo.Client, collectionName string) *mongo.Collection {
collection := client.Database("combinedDB").Collection(collectionName)
return collection
}
func getEnvMongoURI() string {
uri, err := utils.GetEnv("MONGODB_URI")
if err != nil {
panic(err)
}
return uri
}