diff --git a/sync/client/memory.go b/sync/client/memory.go index e7190b4..1b84917 100644 --- a/sync/client/memory.go +++ b/sync/client/memory.go @@ -1,22 +1,45 @@ package client import ( + "slices" + "sync" "time" "go-mod.ewintr.nl/planner/item" ) type Memory struct { + items map[string]item.Item + sync.RWMutex } func NewMemory() *Memory { - return &Memory{} + return &Memory{ + items: make(map[string]item.Item, 0), + } } func (m *Memory) Update(items []item.Item) error { + m.Lock() + defer m.Unlock() + + for _, i := range items { + m.items[i.ID] = i + } + return nil } 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 } diff --git a/sync/client/memory_test.go b/sync/client/memory_test.go new file mode 100644 index 0000000..c1f451c --- /dev/null +++ b/sync/client/memory_test.go @@ -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) + } + }) + } +}