From 3913d9aae6e67daae3c0226b418610f8881a2a1f Mon Sep 17 00:00:00 2001 From: Denis Dorozhkin Date: Thu, 9 Dec 2021 12:28:45 +0200 Subject: [PATCH 1/2] add GetItems method --- cache.go | 15 +++++++++++++++ cache_test.go | 15 +++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/cache.go b/cache.go index 778aaa9..dc22935 100644 --- a/cache.go +++ b/cache.go @@ -457,6 +457,21 @@ func (cache *Cache) GetKeys() []string { return keys } +// GetItems returns a copy of all items in the cache. Returns nil when the cache has been closed. +func (cache *Cache) GetItems() map[string]interface{} { + cache.mutex.Lock() + defer cache.mutex.Unlock() + + if cache.isShutDown { + return nil + } + items := make(map[string]interface{}, len(cache.items)) + for k, item := range cache.items { + items[k] = item.data + } + return items +} + // SetTTL sets the global TTL value for items in the cache, which can be overridden at the item level. func (cache *Cache) SetTTL(ttl time.Duration) error { cache.mutex.Lock() diff --git a/cache_test.go b/cache_test.go index 2d9a894..4d41af7 100644 --- a/cache_test.go +++ b/cache_test.go @@ -829,6 +829,21 @@ func TestCacheGetKeys(t *testing.T) { assert.Equal(t, []string{"hello"}, keys, "Expected keys contains 'hello'") } +func TestCacheGetItems(t *testing.T) { + t.Parallel() + + cache := NewCache() + defer cache.Close() + + items := cache.GetItems() + assert.Empty(t, items, "Expected items to be empty") + + cache.Set("hello", "world") + items = cache.GetItems() + assert.NotEmpty(t, items, "Expected items to be not empty") + assert.Equal(t, map[string]interface{}{"hello": "world"}, items, "Expected items to {'hello': 'world'}") +} + func TestCacheGetWithTTL(t *testing.T) { t.Parallel() From 1f2a82bfbfe9c7dccf4c2e36f2969f8b6f81a3ca Mon Sep 17 00:00:00 2001 From: Denis Dorozhkin Date: Wed, 15 Dec 2021 10:33:36 +0200 Subject: [PATCH 2/2] GetItems: use getItem --- cache.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/cache.go b/cache.go index dc22935..4b2f820 100644 --- a/cache.go +++ b/cache.go @@ -466,8 +466,11 @@ func (cache *Cache) GetItems() map[string]interface{} { return nil } items := make(map[string]interface{}, len(cache.items)) - for k, item := range cache.items { - items[k] = item.data + for k := range cache.items { + item, exists, _ := cache.getItem(k) + if exists { + items[k] = item.data + } } return items }