memory client

This commit is contained in:
Erik Winter 2024-10-10 07:24:49 +02:00
parent 6fe7fe009e
commit ef7beacec8
2 changed files with 85 additions and 2 deletions

View File

@ -1,22 +1,45 @@
package client package client
import ( import (
"slices"
"sync"
"time" "time"
"go-mod.ewintr.nl/planner/item" "go-mod.ewintr.nl/planner/item"
) )
type Memory struct { type Memory struct {
items map[string]item.Item
sync.RWMutex
} }
func NewMemory() *Memory { func NewMemory() *Memory {
return &Memory{} return &Memory{
items: make(map[string]item.Item, 0),
}
} }
func (m *Memory) Update(items []item.Item) error { func (m *Memory) Update(items []item.Item) error {
m.Lock()
defer m.Unlock()
for _, i := range items {
m.items[i.ID] = i
}
return nil return nil
} }
func (m *Memory) Updated(kw []item.Kind, ts time.Time) ([]item.Item, error) { func (m *Memory) Updated(kw []item.Kind, ts time.Time) ([]item.Item, error) {
return nil, nil m.RLock()
defer m.RUnlock()
res := make([]item.Item, 0)
for _, i := range m.items {
if slices.Contains(kw, i.Kind) && (i.Updated.After(ts) || i.Updated.Equal(ts)) {
res = append(res, i)
}
}
return res, nil
} }

View File

@ -0,0 +1,60 @@
package client_test
import (
"testing"
"time"
"github.com/google/go-cmp/cmp"
"go-mod.ewintr.nl/planner/item"
"go-mod.ewintr.nl/planner/sync/client"
)
func TestMemory(t *testing.T) {
t.Parallel()
mem := client.NewMemory()
now := time.Now()
items := []item.Item{
{ID: "a", Kind: item.KindTask, Updated: now.Add(-15 * time.Minute)},
{ID: "b", Kind: item.KindEvent, Updated: now.Add(-10 * time.Minute)},
{ID: "c", Kind: item.KindTask, Updated: now.Add(-5 * time.Minute)},
}
if err := mem.Update(items); err != nil {
t.Errorf("exp nil, got %v", err)
}
for _, tc := range []struct {
name string
ks []item.Kind
ts time.Time
expItems []item.Item
}{
{
name: "empty",
ks: make([]item.Kind, 0),
expItems: make([]item.Item, 0),
},
{
name: "kind",
ks: []item.Kind{item.KindEvent},
expItems: []item.Item{items[1]},
},
{
name: "timestamp",
ks: []item.Kind{item.KindTask, item.KindEvent},
ts: now.Add(-10 * time.Minute),
expItems: items[1:],
},
} {
t.Run(tc.name, func(t *testing.T) {
actItems, actErr := mem.Updated(tc.ks, tc.ts)
if actErr != nil {
t.Errorf("exp nil, got %v", actErr)
}
if diff := cmp.Diff(tc.expItems, actItems); diff != "" {
t.Errorf("(exp +, got -)\n%s", diff)
}
})
}
}