diff --git a/cache.go b/cache.go index 778aaa9..4b2f820 100644 --- a/cache.go +++ b/cache.go @@ -457,6 +457,24 @@ 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 := range cache.items { + item, exists, _ := cache.getItem(k) + if exists { + 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()