-
Notifications
You must be signed in to change notification settings - Fork 0
/
repo.go
99 lines (71 loc) · 1.4 KB
/
repo.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
package repo
import (
"github.com/pkg/errors"
"homework10/internal/app"
"sync"
)
func New() app.Repository {
return &Repo{storage: make(map[int64]interface{}), nextNum: 0}
}
type Repo struct {
storage map[int64]interface{}
nextNum int64
mu sync.Mutex
}
var DefunctEntity = errors.New("there is no entity with this id")
func (a *Repo) Add(e interface{}) error {
a.mu.Lock()
defer a.mu.Unlock()
a.storage[a.nextNum] = e
a.nextNum++
return nil
}
func (a *Repo) Update(id int64, e interface{}) error {
a.mu.Lock()
defer a.mu.Unlock()
_, exists := a.storage[id]
if !exists {
return DefunctEntity
}
a.storage[id] = e
return nil
}
func (a *Repo) Get(id int64) (interface{}, error) {
a.mu.Lock()
defer a.mu.Unlock()
_, exists := a.storage[id]
if !exists {
return nil, DefunctEntity
}
return a.storage[id], nil
}
func (a *Repo) Delete(id int64) error {
a.mu.Lock()
defer a.mu.Unlock()
_, exists := a.storage[id]
if !exists {
return DefunctEntity
}
delete(a.storage, id)
return nil
}
func (a *Repo) CheckIdExist(id int64) bool {
a.mu.Lock()
defer a.mu.Unlock()
_, exists := a.storage[id]
return exists
}
func (a *Repo) GetNextId() int64 {
a.mu.Lock()
defer a.mu.Unlock()
return a.nextNum
}
func (a *Repo) GetArray() []interface{} {
a.mu.Lock()
defer a.mu.Unlock()
arr := make([]interface{}, 0)
for _, e := range a.storage {
arr = append(arr, e)
}
return arr
}