118 lines
2.4 KiB
Go
118 lines
2.4 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"sync"
|
|
|
|
"apps/backend/internal/module/usage/domain"
|
|
)
|
|
|
|
type MemoryStore struct {
|
|
mu sync.Mutex
|
|
events []*domain.Event
|
|
prefs map[int64]*domain.MemberPrefs
|
|
purchases []*domain.Purchase
|
|
}
|
|
|
|
func NewMemory() *MemoryStore {
|
|
return &MemoryStore{
|
|
prefs: map[int64]*domain.MemberPrefs{},
|
|
}
|
|
}
|
|
|
|
func (s *MemoryStore) InsertEvent(_ context.Context, e *domain.Event) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
cp := *e
|
|
s.events = append(s.events, &cp)
|
|
return nil
|
|
}
|
|
|
|
func (s *MemoryStore) ListEvents(_ context.Context, uid int64, monthKey, keyMode string, limit int) ([]*domain.Event, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
var out []*domain.Event
|
|
for i := len(s.events) - 1; i >= 0; i-- {
|
|
e := s.events[i]
|
|
if e.UID != uid {
|
|
continue
|
|
}
|
|
if monthKey != "" && e.MonthKey != monthKey {
|
|
continue
|
|
}
|
|
if keyMode != "" && keyMode != "all" && e.KeyMode != keyMode {
|
|
continue
|
|
}
|
|
cp := *e
|
|
out = append(out, &cp)
|
|
if limit > 0 && len(out) >= limit {
|
|
break
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (s *MemoryStore) ListEventsAll(_ context.Context, monthKey string, limit int) ([]*domain.Event, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
var out []*domain.Event
|
|
for i := len(s.events) - 1; i >= 0; i-- {
|
|
e := s.events[i]
|
|
if monthKey != "" && e.MonthKey != monthKey {
|
|
continue
|
|
}
|
|
cp := *e
|
|
out = append(out, &cp)
|
|
if limit > 0 && len(out) >= limit {
|
|
break
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (s *MemoryStore) GetPrefs(_ context.Context, uid int64) (*domain.MemberPrefs, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if p, ok := s.prefs[uid]; ok {
|
|
cp := *p
|
|
return &cp, nil
|
|
}
|
|
return &domain.MemberPrefs{UID: uid, PlanID: domain.PlanFree}, nil
|
|
}
|
|
|
|
func (s *MemoryStore) SavePrefs(_ context.Context, p *domain.MemberPrefs) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
cp := *p
|
|
s.prefs[p.UID] = &cp
|
|
return nil
|
|
}
|
|
|
|
func (s *MemoryStore) InsertPurchase(_ context.Context, p *domain.Purchase) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
cp := *p
|
|
s.purchases = append(s.purchases, &cp)
|
|
return nil
|
|
}
|
|
|
|
func (s *MemoryStore) ListPurchases(_ context.Context, uid int64, limit int) ([]*domain.Purchase, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
var out []*domain.Purchase
|
|
for i := len(s.purchases) - 1; i >= 0; i-- {
|
|
p := s.purchases[i]
|
|
if p.UID != uid {
|
|
continue
|
|
}
|
|
cp := *p
|
|
out = append(out, &cp)
|
|
if limit > 0 && len(out) >= limit {
|
|
break
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
var _ domain.Repository = (*MemoryStore)(nil)
|