-
Notifications
You must be signed in to change notification settings - Fork 1
/
collection.go
122 lines (90 loc) · 2.16 KB
/
collection.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"sync"
"time"
)
// A collection of Items.
type Collection struct {
Items map[string]Item `json:"items"`
cMu sync.RWMutex
}
type Collections map[string]Collection
var collections = make(Collections)
func (collections Collections) ListCollections() Collections {
gMu.RLock()
defer gMu.RUnlock()
return collections
}
func (collections Collections) GetCollection(id string) Collection {
gMu.RLock()
defer gMu.RUnlock()
return collections[id]
}
func (collections Collections) CreateEmptyCollection(id string) Collection {
var c Collection
c.Items = make(Items)
collections[id] = c
return c
}
func (collections Collections) AddItem(collectionId string, itemId string, data interface{}) interface{} {
gMu.Lock()
defer gMu.Unlock()
collection, present := collections[collectionId]
if present == false {
collection = collections.CreateEmptyCollection(collectionId)
}
var item Item
item.Data = data
item.Created = time.Now().Unix()
collection.Items[itemId] = item
result.Status = "OK"
return result
}
func (collections Collections) DeleteOneCollection(id string) Result {
gMu.Lock()
defer gMu.Unlock()
delete(collections, id)
result.Status = "OK"
return result
}
func (collections Collections) FlushCollections() Result {
gMu.Lock()
defer gMu.Unlock()
for k := range collections {
delete(collections, k)
}
result.Status = "OK"
return result
}
func (collection Collection) GetItems() Items {
collection.cMu.RLock()
defer collection.cMu.RUnlock()
return collection.Items
}
func (collection Collection) FindOneItemById(itemId string) Item {
collection.cMu.RLock()
defer collection.cMu.RUnlock()
i, present := collection.Items[itemId]
if present == false {
return Item{}
}
return i
}
func (collection Collection) DeleteOneItemById(itemId string) Result {
collection.cMu.Lock()
defer collection.cMu.Unlock()
items := collection.Items
delete(items, itemId)
result.Status = "OK"
return result
}
func (collection Collection) FlushItems() Result {
collection.cMu.Lock()
defer collection.cMu.Unlock()
items := collection.Items
for k := range items {
delete(items, k)
}
result.Status = "OK"
return result
}