Skip to content

Commit c853f04

Browse files
authored
Merge pull request #89 from Flavore669/develop
Created singleton (Issue #69)
2 parents 32af6da + ed50365 commit c853f04

File tree

1 file changed

+31
-20
lines changed

1 file changed

+31
-20
lines changed

uploader/database.go

Lines changed: 31 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,56 @@
11
/*
2-
This file is responsible for providing various useful database functions.
2+
This file is responsible for providing various useful database functions.
33
*/
4-
54
package uploader
65

76
import (
8-
//"go.mongodb.org/mongo-driver/bson"
9-
//"go.mongodb.org/mongo-driver/bson/primitive"
107
"context"
118
"log"
129
"os"
10+
"sync"
1311
"time"
1412

1513
"github.com/UTDNebula/api-tools/utils"
1614
"go.mongodb.org/mongo-driver/mongo"
1715
"go.mongodb.org/mongo-driver/mongo/options"
1816
)
1917

18+
// TODO: Replace instances and check
19+
type DBSingleton struct {
20+
client *mongo.Client
21+
}
22+
23+
var dbInstance *DBSingleton
24+
var once sync.Once
25+
2026
func connectDB() *mongo.Client {
27+
once.Do(func() {
28+
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
29+
defer cancel()
2130

22-
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
23-
defer cancel()
31+
opts := options.Client().ApplyURI(getEnvMongoURI())
2432

25-
opts := options.Client().ApplyURI(getEnvMongoURI())
33+
client, err := mongo.Connect(ctx, opts)
34+
if err != nil {
35+
log.Panic("Unable to create MongoDB client and connect to database")
36+
os.Exit(1)
37+
}
2638

27-
client, err := mongo.Connect(ctx, opts)
28-
if err != nil {
29-
log.Panic("Unable to create MongoDB client and connect to database")
30-
os.Exit(1)
31-
}
39+
// ping the database
40+
err = client.Ping(ctx, nil)
41+
if err != nil {
42+
log.Panic("Unable to ping database")
43+
os.Exit(1)
44+
}
3245

33-
//ping the database
34-
err = client.Ping(ctx, nil)
35-
if err != nil {
36-
log.Panic("Unable to ping database")
37-
os.Exit(1)
38-
}
46+
log.Println("Connected to MongoDB")
3947

40-
log.Println("Connected to MongoDB")
48+
dbInstance = &DBSingleton{
49+
client: client,
50+
}
51+
})
4152

42-
return client
53+
return dbInstance.client
4354
}
4455

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

0 commit comments

Comments
 (0)