-
Notifications
You must be signed in to change notification settings - Fork 42
/
storage.go
107 lines (83 loc) · 2.34 KB
/
storage.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package storage
import (
"fmt"
"regexp"
"sync"
)
var currentStorage Storage
var mu sync.Mutex
type Storage interface {
Write(collection, key string, v interface{}) error
Read(collection, key string, v interface{}) error
GetKeys(collection string) ([]string, error)
Delete(collection, key string) error
}
// allowed characters for stage keys/collection
var keyRegexp = regexp.MustCompile(`^[\w\-,+@]+$`)
// InitStorage registers a local directory as JSON file Storage
func InitStorage(path string) error {
var err error
if path == "" {
currentStorage = newMemoryStorage()
} else {
currentStorage, err = newFileStorage(path)
}
return err
}
// SetStorage provide Storage to persist data for bot usage
func SetStorage(storage Storage) {
currentStorage = storage
}
// Write stores one value in the persistent Storage
func Write(collection string, key string, v interface{}) error {
if err := validateKey(collection, key); err != nil {
return err
}
return getStorage().Write(collection, key, v)
}
// Read will load the stored data for one entry (using reference) to avoid allocation
func Read(collection string, key string, v interface{}) error {
if err := validateKey(collection, key); err != nil {
return err
}
return getStorage().Read(collection, key, v)
}
// GetKeys will return the (json) strings of a collection
func GetKeys(collection string) ([]string, error) {
if err := validateKey(collection); err != nil {
return nil, err
}
return getStorage().GetKeys(collection)
}
// DeleteCollection delete all entries of a collection
func DeleteCollection(collection string) error {
if err := validateKey(collection); err != nil {
return err
}
return getStorage().Delete(collection, "")
}
// Delete will return a single entry of a collection
func Delete(collection string, key string) error {
if err := validateKey(collection, key); err != nil {
return err
}
return getStorage().Delete(collection, key)
}
// check if a given key/collection only contains a subset of valid characters
func validateKey(keys ...string) error {
for _, key := range keys {
if !keyRegexp.MatchString(key) {
return fmt.Errorf("invalid Storage key: %s", key)
}
}
return nil
}
func getStorage() Storage {
if currentStorage != nil {
return currentStorage
}
mu.Lock()
defer mu.Unlock()
currentStorage = newMemoryStorage()
return currentStorage
}