-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.go
56 lines (49 loc) · 1.47 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
package models
import (
"context"
"fmt"
"log"
"time"
"github.com/golang-friends/slack-clone/authservice/configs"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// Database represents the information needed to connect to a database
type Database struct {
DBURI string `json:"dburi"`
DBName string `json:"dbname"`
DBUser string `json:"dbuser"`
DBPassword string `json:"dbpassword"`
}
// Db ...
var Db mongo.Database
// ConnectToDB ...
func ConnectToDB(conf configs.Configuration) {
db := Database{
DBURI: conf.DB.DBURI,
DBUser: conf.DB.DBUser,
DBPassword: conf.DB.DBPass,
DBName: conf.DB.DBName,
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%s@%s", db.DBUser, db.DBPassword, db.DBURI)))
if err != nil {
log.Fatal("Error connecting to DB: ", err.Error())
}
Db = *client.Database(db.DBName)
}
// ConnectToTestDB takes in a url string for testing purposes
func ConnectToTestDB(url string) {
ctx := context.Background()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(url))
if err != nil {
log.Fatal("Error connecting to DB: ", err.Error())
}
Db = *client.Database("auth_service_test")
collections, _ := Db.ListCollectionNames(ctx, bson.M{})
for _, collection := range collections {
Db.Collection(collection).Drop(ctx)
}
}