|
1 | 1 | /* |
2 | | - This file is responsible for providing various useful database functions. |
| 2 | +This file is responsible for providing various useful database functions. |
3 | 3 | */ |
4 | | - |
5 | 4 | package uploader |
6 | 5 |
|
7 | 6 | import ( |
8 | | - //"go.mongodb.org/mongo-driver/bson" |
9 | | - //"go.mongodb.org/mongo-driver/bson/primitive" |
10 | 7 | "context" |
11 | 8 | "log" |
12 | 9 | "os" |
| 10 | + "sync" |
13 | 11 | "time" |
14 | 12 |
|
15 | 13 | "github.com/UTDNebula/api-tools/utils" |
16 | 14 | "go.mongodb.org/mongo-driver/mongo" |
17 | 15 | "go.mongodb.org/mongo-driver/mongo/options" |
18 | 16 | ) |
19 | 17 |
|
| 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 | + |
20 | 26 | func connectDB() *mongo.Client { |
| 27 | + once.Do(func() { |
| 28 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 29 | + defer cancel() |
21 | 30 |
|
22 | | - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
23 | | - defer cancel() |
| 31 | + opts := options.Client().ApplyURI(getEnvMongoURI()) |
24 | 32 |
|
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 | + } |
26 | 38 |
|
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 | + } |
32 | 45 |
|
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") |
39 | 47 |
|
40 | | - log.Println("Connected to MongoDB") |
| 48 | + dbInstance = &DBSingleton{ |
| 49 | + client: client, |
| 50 | + } |
| 51 | + }) |
41 | 52 |
|
42 | | - return client |
| 53 | + return dbInstance.client |
43 | 54 | } |
44 | 55 |
|
45 | 56 | func getCollection(client *mongo.Client, collectionName string) *mongo.Collection { |
|
0 commit comments