-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo_data_cache.go
92 lines (81 loc) · 2.06 KB
/
mongo_data_cache.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
89
90
91
92
package main
import (
"context"
"os"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type mongoDataCache struct {
client *mongo.Client
collection *mongo.Collection
}
func newMongoDataCache() *mongoDataCache {
mdc := new(mongoDataCache)
clientOptions := options.Client().ApplyURI(os.Getenv("MONGO_URL"))
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
Fatal(err)
}
mdc.client = client
err = client.Ping(context.TODO(), nil)
if err != nil {
Fatal(err)
}
mdc.collection = mdc.client.Database("etsello").Collection("users")
Info("Connected to db and created collections.")
return mdc
}
func (mdc mongoDataCache) saveDetailsToCache(userID int, info userInfo) {
filter := bson.D{primitive.E{Key: "_id", Value: userID}}
bsonDocument, _ := toDoc(info)
upsertValue := true
uOptions := options.MergeReplaceOptions()
uOptions.Upsert = &upsertValue
_, err := mdc.collection.ReplaceOne(context.TODO(), filter, bsonDocument, uOptions)
if err != nil {
Fatal(err)
}
}
func (mdc mongoDataCache) getUserInfo(userID int) (*userInfo, error) {
var result userInfo
filter := bson.D{primitive.E{Key: "_id", Value: userID}}
err := mdc.collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
Error(err)
return nil, err
}
return &result, nil
}
func (mdc mongoDataCache) getUserMap() map[int]userInfo {
results := make(map[int]userInfo)
cur, err := mdc.collection.Find(context.TODO(), bson.D{{}})
if err != nil {
Fatal(err)
}
for cur.Next(context.TODO()) {
var elem userInfo
err := cur.Decode(&elem)
if err != nil {
Fatal(err)
}
results[elem.UserID] = elem
}
return results
}
func (mdc mongoDataCache) disconnectCache() {
err := mdc.client.Disconnect(context.TODO())
if err != nil {
Fatal(err)
}
Info("Connection to mongodb closed.")
}
func toDoc(v interface{}) (doc *bson.D, err error) {
data, err := bson.Marshal(v)
if err != nil {
return
}
err = bson.Unmarshal(data, &doc)
return
}