/
IssueRepository.go
78 lines (68 loc) · 1.74 KB
/
IssueRepository.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
package memory
import (
"errors"
"github.com/patrickmn/go-cache"
"github.com/PacktPublishing/Advanced-Go-Programming-in-7-Days/Day-6/3-Domain-Driver-Design/easy-issues/domain"
)
const (
IssuesAllKey = "Issues:all"
IssueLastId = "Issue:lastId"
)
// IssueRepository concrete implementation of in-memory db
type IssueRepository struct {
db *cache.Cache
}
func NewIssueRepository() *IssueRepository {
db := cache.New(cache.NoExpiration, cache.NoExpiration)
db.SetDefault(IssueLastId, int64(0))
db.SetDefault(IssuesAllKey, []*domain.Issue{})
return &IssueRepository{
db: db,
}
}
func (r IssueRepository)All() ([]*domain.Issue, error) {
result, ok := r.db.Get(IssuesAllKey)
if ok {
return result.([]*domain.Issue), nil
} else {
return nil, errors.New("Empty list")
}
}
func (r IssueRepository)GetById(id int64) (*domain.Issue, error) {
result, ok := r.db.Get(IssuesAllKey)
if ok {
items := result.([]*domain.Issue)
for _, issue := range items {
if issue.Id == id {
return issue, nil
}
}
return nil, errors.New("Not Found")
}
return nil, errors.New("Not Found")
}
func (r *IssueRepository)Create(u *domain.Issue) error {
id, _ := r.db.IncrementInt64(IssueLastId, int64(1))
u.Id = id
result, ok := r.db.Get(IssuesAllKey)
if ok {
result = append(result.([]*domain.Issue), u)
r.db.Set(IssuesAllKey, result, cache.NoExpiration)
}
return nil
}
func (r *IssueRepository)Delete(id int64) error {
result, ok := r.db.Get(IssuesAllKey)
if ok {
items := result.([]*domain.Issue)
for i, issue := range items {
if issue.Id == id {
items = append(items[:i], items[i+1:]...)
r.db.Set(IssuesAllKey, items, cache.NoExpiration)
return nil
}
}
return errors.New("Not Found")
}
return errors.New("Not Found")
}