Skip to content

Commit

Permalink
add GetItems method
Browse files Browse the repository at this point in the history
  • Loading branch information
DoubleDi authored and ReneKroon committed Dec 15, 2021
1 parent de26703 commit 14f5461
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
15 changes: 15 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
15 changes: 15 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down

0 comments on commit 14f5461

Please sign in to comment.