-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstore.go
90 lines (76 loc) · 1.56 KB
/
store.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
package memory
import (
"context"
"sync"
"time"
"github.com/code-payments/code-server/pkg/code/data/paywall"
)
type store struct {
mu sync.Mutex
records []*paywall.Record
last uint64
}
func New() paywall.Store {
return &store{
records: make([]*paywall.Record, 0),
last: 0,
}
}
func (s *store) reset() {
s.mu.Lock()
s.records = make([]*paywall.Record, 0)
s.last = 0
s.mu.Unlock()
}
// Put implements paywall.Store.Put
func (s *store) Put(_ context.Context, data *paywall.Record) error {
if err := data.Validate(); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
s.last++
if item := s.find(data); item != nil {
return paywall.ErrPaywallExists
} else {
if data.Id == 0 {
data.Id = s.last
}
if data.CreatedAt.IsZero() {
data.CreatedAt = time.Now()
}
c := data.Clone()
s.records = append(s.records, &c)
}
return nil
}
// GetByShortPath implements paywall.Store.GetByShortPath
func (s *store) GetByShortPath(_ context.Context, path string) (*paywall.Record, error) {
s.mu.Lock()
defer s.mu.Unlock()
item := s.findByShortPath(path)
if item == nil {
return nil, paywall.ErrPaywallNotFound
}
cloned := item.Clone()
return &cloned, nil
}
func (s *store) find(data *paywall.Record) *paywall.Record {
for _, item := range s.records {
if item.Id == data.Id {
return item
}
if item.ShortPath == data.ShortPath {
return item
}
}
return nil
}
func (s *store) findByShortPath(path string) *paywall.Record {
for _, item := range s.records {
if item.ShortPath == path {
return item
}
}
return nil
}