-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstore.go
121 lines (101 loc) · 2.38 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
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
package memory
import (
"context"
"sync"
"time"
"github.com/code-payments/code-server/pkg/code/data/login"
)
type store struct {
mu sync.Mutex
records []*login.MultiRecord
}
// New returns a new in memory login.Store
func New() login.Store {
return &store{}
}
// Save implements login.Store.Save
func (s *store) Save(_ context.Context, data *login.MultiRecord) error {
s.mu.Lock()
defer s.mu.Unlock()
var found bool
for _, item := range s.records {
if item.AppInstallId == data.AppInstallId {
item.Owners = append([]string(nil), data.Owners...)
item.LastUpdatedAt = time.Now()
item.CopyTo(data)
found = true
continue
}
var owners []string
for _, owner := range item.Owners {
var excludeOwner bool
for _, updatedOwner := range data.Owners {
if owner == updatedOwner {
excludeOwner = true
break
}
}
if !excludeOwner {
owners = append(owners, owner)
}
}
item.Owners = owners
item.LastUpdatedAt = time.Now()
}
if !found {
data.LastUpdatedAt = time.Now()
cloned := data.Clone()
s.records = append(s.records, &cloned)
}
return nil
}
// GetAllByInstallId implements login.Store.GetAllByInstallId
func (s *store) GetAllByInstallId(_ context.Context, appInstallId string) (*login.MultiRecord, error) {
s.mu.Lock()
defer s.mu.Unlock()
if item := s.findByAppInstallId(appInstallId); item != nil {
if len(item.Owners) == 0 {
return nil, login.ErrLoginNotFound
}
cloned := item.Clone()
return &cloned, nil
}
return nil, login.ErrLoginNotFound
}
// GetLatestByOwner implements login.Store.GetLatestByOwner
func (s *store) GetLatestByOwner(_ context.Context, owner string) (*login.Record, error) {
s.mu.Lock()
defer s.mu.Unlock()
item := s.findByOwner(owner)
if item == nil {
return nil, login.ErrLoginNotFound
}
return &login.Record{
AppInstallId: item.AppInstallId,
Owner: owner,
LastUpdatedAt: item.LastUpdatedAt,
}, nil
}
func (s *store) findByAppInstallId(appInstallId string) *login.MultiRecord {
for _, item := range s.records {
if item.AppInstallId == appInstallId {
return item
}
}
return nil
}
func (s *store) findByOwner(owner string) *login.MultiRecord {
for _, item := range s.records {
for _, itemOwner := range item.Owners {
if itemOwner == owner {
return item
}
}
}
return nil
}
func (s *store) reset() {
s.mu.Lock()
defer s.mu.Unlock()
s.records = nil
}