-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathchain.go
91 lines (73 loc) · 1.87 KB
/
chain.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 chain provides chaining cache drivers operations, in case of failure
// the driver try to apply using the next driver informed, until fail.
package chain
import (
"errors"
"time"
"github.com/faabiosr/cachego"
)
type (
chain struct {
drivers []cachego.Cache
}
)
// New creates an instance of Chain cache driver
func New(drivers ...cachego.Cache) cachego.Cache {
return &chain{drivers}
}
// Contains checks if the cached key exists in one of the cache storages
func (c *chain) Contains(key string) bool {
for _, driver := range c.drivers {
if driver.Contains(key) {
return true
}
}
return false
}
// Delete the cached key in all cache storages
func (c *chain) Delete(key string) error {
for _, driver := range c.drivers {
if err := driver.Delete(key); err != nil {
return err
}
}
return nil
}
// Fetch retrieves the value of one of the registred cache storages
func (c *chain) Fetch(key string) (string, error) {
for _, driver := range c.drivers {
value, err := driver.Fetch(key)
if err == nil {
return value, nil
}
}
return "", errors.New("key not found in cache chain")
}
// FetchMulti retrieves multiple cached values from one of the registred cache storages
func (c *chain) FetchMulti(keys []string) map[string]string {
result := make(map[string]string)
for _, key := range keys {
if value, err := c.Fetch(key); err == nil {
result[key] = value
}
}
return result
}
// Flush removes all cached keys of the registered cache storages
func (c *chain) Flush() error {
for _, driver := range c.drivers {
if err := driver.Flush(); err != nil {
return err
}
}
return nil
}
// Save a value in all cache storages by key
func (c *chain) Save(key string, value string, lifeTime time.Duration) error {
for _, driver := range c.drivers {
if err := driver.Save(key, value, lifeTime); err != nil {
return err
}
}
return nil
}