/
mongo.go
88 lines (73 loc) · 1.92 KB
/
mongo.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package database
import (
"context"
"errors"
"fmt"
"sync"
"github.com/kavkaco/Kavka-Core/config"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var (
mongoLock = &sync.Mutex{}
mongoInstance *mongo.Database
)
var (
UsersCollection = "users"
ChatsCollection = "chats"
)
func NewMongoDBConnectionString(host string, port int, username string, password string) string {
return fmt.Sprintf("mongodb://%s:%s@%s:%d", username, password, host, port) //nolint
}
func GetMongoDBInstance(mongoConfigs config.Mongo) (*mongo.Database, error) {
if mongoInstance == nil {
mongoLock.Lock()
defer mongoLock.Unlock()
connectionString := NewMongoDBConnectionString(
mongoConfigs.Host,
mongoConfigs.Port,
mongoConfigs.Username,
mongoConfigs.Password,
)
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(connectionString))
if err != nil {
return nil, err
}
mongoInstance = client.Database(mongoConfigs.DBName)
collectionsConfigurations(mongoInstance)
}
return mongoInstance, nil
}
func collectionsConfigurations(db *mongo.Database) {
db.Collection(UsersCollection).Indexes().CreateOne(context.Background(), mongo.IndexModel{ //nolint
Keys: bson.D{{Key: "phone", Value: 1}},
Options: options.Index().SetUnique(true),
})
db.Collection(UsersCollection).Indexes().CreateOne(context.Background(), mongo.IndexModel{ //nolint
Keys: bson.D{{Key: "username", Value: 1}},
Options: options.Index().SetUnique(true),
})
}
func IsDuplicateKeyError(err error) bool {
var e mongo.WriteException
if errors.As(err, &e) {
for _, we := range e.WriteErrors {
if we.Code == 11000 {
return true
}
}
}
return false
}
func IsRowExistsError(err error) bool {
var e mongo.WriteException
if errors.As(err, &e) {
for _, we := range e.WriteErrors {
if we.Code == 121 {
return true
}
}
}
return false
}