-
Notifications
You must be signed in to change notification settings - Fork 0
/
block_list.go
86 lines (70 loc) · 2.15 KB
/
block_list.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
package memorystorage
import (
"context"
"github.com/dantin/cubit/model"
"github.com/dantin/cubit/model/serializer"
)
// BlockList represents an in-memory block-list storage.
type BlockList struct {
*memoryStorage
}
// NewBlockList returns an instance of BlockList in-memory storage.
func NewBlockList() *BlockList {
return &BlockList{memoryStorage: newStorage()}
}
// InsertBlockListItem inserts a block list item entity into storage if not previously inserted.
func (m *BlockList) InsertBlockListItem(_ context.Context, item *model.BlockListItem) error {
return m.updateInWriteLock(blockListItemKey(item.Username), func(b []byte) ([]byte, error) {
var items []model.BlockListItem
if len(b) > 0 {
if err := serializer.DeserializeSlice(b, &items); err != nil {
return nil, err
}
}
for _, itm := range items {
if itm.JID == item.JID {
return b, nil // already inserted
}
}
items = append(items, *item)
output, err := serializer.SerializeSlice(&items)
if err != nil {
return nil, err
}
return output, nil
})
}
// DeleteBlockListItem deletes a block list item entity from storage.
func (m *BlockList) DeleteBlockListItem(_ context.Context, item *model.BlockListItem) error {
return m.updateInWriteLock(blockListItemKey(item.Username), func(b []byte) ([]byte, error) {
var items []model.BlockListItem
if len(b) > 0 {
if err := serializer.DeserializeSlice(b, &items); err != nil {
return nil, err
}
}
for i, itm := range items {
if itm.JID == item.JID {
items = append(items[:i], items[i+1:]...)
output, err := serializer.SerializeSlice(&items)
if err != nil {
return nil, err
}
return output, nil
}
}
return b, nil // not present
})
}
// FetchBlockListItems retrieves from storage all block list item entities associated to a given user.
func (m *BlockList) FetchBlockListItems(_ context.Context, username string) ([]model.BlockListItem, error) {
var items []model.BlockListItem
_, err := m.getEntities(blockListItemKey(username), &items)
if err != nil {
return nil, err
}
return items, nil
}
func blockListItemKey(username string) string {
return "blockListItems:" + username
}