-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
db.go
74 lines (56 loc) · 1.46 KB
/
db.go
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
68
69
70
71
72
73
74
package utils
import (
"context"
"os"
"errors"
"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() error {
if(GetBaseMainConfig().DisableUserManagement) {
return errors.New("User Management is disabled")
}
uri := GetBaseMainConfig().MongoDB + "/?retryWrites=true&w=majority"
if(client != nil && client.Ping(context.TODO(), readpref.Primary()) == nil) {
return nil
}
Log("(Re) Connecting to the database...")
var err error
client, err = mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil {
return err
}
defer func() {
}()
// Ping the primary
if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {
return err
}
Log("Successfully connected to the database.")
return nil
}
func DisconnectDB() {
if err := client.Disconnect(context.TODO()); err != nil {
Fatal("DB", err)
}
client = nil
}
func GetCollection(applicationId string, collection string) (*mongo.Collection, error) {
if client == nil {
errCo := DB()
if errCo != nil {
return nil, errCo
}
}
name := os.Getenv("MONGODB_NAME"); if name == "" {
name = "COSMOS"
}
Debug("Getting collection " + applicationId + "_" + collection + " from database " + name)
c := client.Database(name).Collection(applicationId + "_" + collection)
return c, nil
}
// func query(q string) (*sql.Rows, error) {
// return db.Query(q)
// }