-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathdatabag.go
65 lines (55 loc) · 1.42 KB
/
databag.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
package ussd
import (
"encoding/json"
"github.com/samora/ussd-go/sessionstores"
)
// DataBag is a key-value store.
// Used to store data that will be available across USSD session's
// request.
type DataBag struct {
name string
store sessionstores.Store
}
func newDataBag(store sessionstores.Store, request *Request) *DataBag {
name := request.Mobile + "DataBag"
return &DataBag{
name: name,
store: store,
}
}
// Set value in databag
func (d DataBag) Set(key, value string) error {
return d.store.HashSetValue(d.name, key, value)
}
// Get value from databag
func (d DataBag) Get(key string) (string, error) {
return d.store.HashGetValue(d.name, key)
}
// Exists verifies if value is in databag
func (d DataBag) Exists(key string) bool {
return d.store.HashValueExists(d.name, key)
}
// Delete value from databag
func (d DataBag) Delete(key string) error {
return d.store.HashDeleteValue(d.name, key)
}
// Clear databag
func (d DataBag) Clear() error {
return d.store.HashDelete(d.name)
}
// SetMarshal marshals v into json and puts in databag
func (d DataBag) SetMarshaled(key string, v interface{}) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
return d.Set(key, string(b))
}
// GetUnmarshal retrieves json from databag and unmarshals into v
func (d DataBag) GetUnmarshaled(key string, v interface{}) error {
str, err := d.Get(key)
if err != nil {
return err
}
return json.Unmarshal([]byte(str), v)
}