-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.go
76 lines (67 loc) · 1.38 KB
/
memory.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
package storage
import (
"errors"
"fmt"
"sync"
"github.com/zatamine/uuid"
)
type memory[T model] struct {
m sync.Mutex
data map[string]T
}
func NewMemory[T model](data map[string]T) Storage[T] {
var newData map[string]T
if len(data) <= 0 {
newData = make(map[string]T)
} else {
newData = data
}
return &memory[T]{
data: newData,
}
}
func (m *memory[T]) Create(item *T) error {
m.m.Lock()
defer m.m.Unlock()
id := uuid.FromString(fmt.Sprintf("%v", item)).String()
m.data[id] = *item
return nil
}
func (m *memory[T]) FindOne(id string) (*T, error) {
m.m.Lock()
defer m.m.Unlock()
item, ok := m.data[id]
if !ok {
errorMsg := fmt.Sprintf("id '%s' not found in memory", id)
return nil, errors.New(errorMsg)
}
return &item, nil
}
func (m *memory[T]) Update(item T) error {
m.m.Lock()
defer m.m.Unlock()
id := item.ID()
if _, ok := m.data[id]; !ok {
errorMsg := fmt.Sprintf("Cannot update item with id '%s'", id)
return errors.New(errorMsg)
}
m.data[id] = item
return nil
}
func (m *memory[T]) Delete(id string) error {
m.m.Lock()
defer m.m.Unlock()
if _, ok := m.data[id]; !ok {
errorMsg := fmt.Sprintf("Cannot delete item with id '%s'", id)
return errors.New(errorMsg)
}
delete(m.data, id)
return nil
}
func (m *memory[T]) FindAll() ([]T, error) {
items := make([]T, 0)
for _, d := range m.data {
items = append(items, d)
}
return items, nil
}