-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
48 lines (40 loc) · 1.03 KB
/
connection.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
package db
import (
"context"
"log"
"github.com/nmarsollier/ordersgo/tools/env"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/x/mongo/driver/topology"
)
var database *mongo.Database
// Get the mongo database
func Get() (*mongo.Database, error) {
if database == nil {
clientOptions := options.Client().ApplyURI(env.Get().MongoURL)
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
return nil, err
}
database = client.Database("orders_go")
}
return database, nil
}
// CheckError función a llamar cuando se produce un error de db
func CheckError(err interface{}) {
if err == topology.ErrServerSelectionTimeout {
database = nil
}
}
// IsUniqueKeyError retorna true si el error es de indice único
func IsUniqueKeyError(err error) bool {
if wErr, ok := err.(mongo.WriteException); ok {
for i := 0; i < len(wErr.WriteErrors); i++ {
if wErr.WriteErrors[i].Code == 11000 {
return true
}
}
}
return false
}