-
Notifications
You must be signed in to change notification settings - Fork 24
/
mongo.go
91 lines (71 loc) · 1.94 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
89
90
91
package mongo
import (
"errors"
"time"
"github.com/faabiosr/cachego"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type (
mongo struct {
collection *mgo.Collection
}
mongoContent struct {
Duration int64
Key string `bson:"_id"`
Value string
}
)
// New creates an instance of Mongo cache driver
func New(collection *mgo.Collection) cachego.Cache {
return &mongo{collection}
}
// Contains checks if cached key exists in Mongo storage
func (m *mongo) Contains(key string) bool {
_, err := m.Fetch(key)
return err == nil
}
// Delete the cached key from Mongo storage
func (m *mongo) Delete(key string) error {
return m.collection.Remove(bson.M{"_id": key})
}
// Fetch retrieves the cached value from key of the Mongo storage
func (m *mongo) Fetch(key string) (string, error) {
content := &mongoContent{}
if err := m.collection.Find(bson.M{"_id": key}).One(content); err != nil {
return "", err
}
if content.Duration == 0 {
return content.Value, nil
}
if content.Duration <= time.Now().Unix() {
_ = m.Delete(key)
return "", errors.New("cache expired")
}
return content.Value, nil
}
// FetchMulti retrieves multiple cached value from keys of the Mongo storage
func (m *mongo) FetchMulti(keys []string) map[string]string {
result := make(map[string]string)
iter := m.collection.Find(bson.M{"_id": bson.M{"$in": keys}}).Iter()
content := &mongoContent{}
for iter.Next(content) {
result[content.Key] = content.Value
}
return result
}
// Flush removes all cached keys of the Mongo storage
func (m *mongo) Flush() error {
_, err := m.collection.RemoveAll(bson.M{})
return err
}
// Save a value in Mongo storage by key
func (m *mongo) Save(key string, value string, lifeTime time.Duration) error {
duration := int64(0)
if lifeTime > 0 {
duration = time.Now().Unix() + int64(lifeTime.Seconds())
}
content := &mongoContent{duration, key, value}
_, err := m.collection.Upsert(bson.M{"_id": key}, content)
return err
}