-
Notifications
You must be signed in to change notification settings - Fork 27
/
db.go
57 lines (46 loc) · 1.1 KB
/
db.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
package slick
import (
"encoding/json"
"fmt"
"github.com/boltdb/bolt"
)
const slickDBDefaultBucket = "slick"
// GetDBKey retrieves a `key` from persistent storage and JSON
// unmarshales it into `v`. We need to `Update` otherwise
// CreateBucketIfNotExists cannot create a bucket and returns
// an error immediately.
func (bot *Bot) GetDBKey(key string, v interface{}) error {
return bot.DB.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte(slickDBDefaultBucket))
if err != nil {
return err
}
val := bucket.Get([]byte(key))
if val == nil {
return fmt.Errorf("not found")
}
err = json.Unmarshal(val, &v)
if err != nil {
return err
}
return nil
})
}
// SetDBKey sets a
func (bot *Bot) PutDBKey(key string, v interface{}) error {
return bot.DB.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte(slickDBDefaultBucket))
if err != nil {
return err
}
jsonRes, err := json.Marshal(v)
if err != nil {
return err
}
err = bucket.Put([]byte(key), jsonRes)
if err != nil {
return err
}
return nil
})
}