generated from mattermost/mattermost-plugin-starter-template
-
Notifications
You must be signed in to change notification settings - Fork 3
/
kv_bookmarks.go
62 lines (50 loc) · 1.23 KB
/
kv_bookmarks.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
package bookmarks
import (
"encoding/json"
"fmt"
"github.com/pkg/errors"
)
// StoreBookmarksKey is the key used to store bookmarks in the plugin KV store
const StoreBookmarksKey = "bookmarks"
func GetBookmarksKey(userID string) string {
return fmt.Sprintf("%s_%s", StoreBookmarksKey, userID)
}
// storeBookmarks stores all the users bookmarks
func (b *Bookmarks) StoreBookmarks() error {
bb, jsonErr := json.Marshal(b)
if jsonErr != nil {
return jsonErr
}
key := GetBookmarksKey(b.userID)
appErr := b.api.KVSet(key, bb)
if appErr != nil {
return appErr
}
return nil
}
// FromJSON returns unmarshalled bookmark or initialized bookmarks if
// bytes are empty
func FromJSON(bytes []byte) (*Bookmarks, error) {
bmarks := &Bookmarks{
ByID: make(map[string]*Bookmark),
}
if len(bytes) != 0 {
jsonErr := json.Unmarshal(bytes, &bmarks)
if jsonErr != nil {
return nil, jsonErr
}
}
return bmarks, nil
}
// DeleteBookmark deletes a bookmark from the store
func (b *Bookmarks) DeleteBookmark(bmarkID string) error {
_, ok := b.exists(bmarkID)
if !ok {
return errors.New(fmt.Sprintf("Bookmark `%v` does not exist", bmarkID))
}
delete(b.ByID, bmarkID)
if err := b.StoreBookmarks(); err != nil {
return err
}
return nil
}