Fetch does not return stale items
This commit is contained in:
8
cache.go
8
cache.go
@@ -81,12 +81,12 @@ func (c *Cache) Replace(key string, value interface{}) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// Attempts to get the value from the cache and calles fetch on a miss.
|
// Attempts to get the value from the cache and calles fetch on a miss (missing
|
||||||
// If fetch returns an error, no value is cached and the error is returned back
|
// or stale item). If fetch returns an error, no value is cached and the error
|
||||||
// to the caller.
|
// is returned back to the caller.
|
||||||
func (c *Cache) Fetch(key string, duration time.Duration, fetch func() (interface{}, error)) (*Item, error) {
|
func (c *Cache) Fetch(key string, duration time.Duration, fetch func() (interface{}, error)) (*Item, error) {
|
||||||
item := c.Get(key)
|
item := c.Get(key)
|
||||||
if item != nil {
|
if item != nil && !item.Expired() {
|
||||||
return item, nil
|
return item, nil
|
||||||
}
|
}
|
||||||
value, err := fetch()
|
value, err := fetch()
|
||||||
|
@@ -1,10 +1,11 @@
|
|||||||
package ccache
|
package ccache
|
||||||
|
|
||||||
import (
|
import (
|
||||||
. "github.com/karlseguin/expect"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
. "github.com/karlseguin/expect"
|
||||||
)
|
)
|
||||||
|
|
||||||
type CacheTests struct{}
|
type CacheTests struct{}
|
||||||
@@ -22,6 +23,22 @@ func (_ CacheTests) DeletesAValue() {
|
|||||||
Expect(cache.Get("worm").Value()).To.Equal("sand")
|
Expect(cache.Get("worm").Value()).To.Equal("sand")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (_ CacheTests) FetchesExpiredItems() {
|
||||||
|
cache := New(Configure())
|
||||||
|
fn := func() (interface{}, error) { return "moo-moo", nil }
|
||||||
|
|
||||||
|
cache.Set("beef", "moo", time.Second)
|
||||||
|
Expect(cache.Get("beef").Value()).To.Equal("moo")
|
||||||
|
|
||||||
|
out, _ := cache.Fetch("beef", time.Second, fn)
|
||||||
|
Expect(out.Value()).To.Equal("moo")
|
||||||
|
|
||||||
|
time.Sleep(2 * time.Second)
|
||||||
|
|
||||||
|
out2, _ := cache.Fetch("beef", time.Second, fn)
|
||||||
|
Expect(out2.Value()).To.Equal("moo-moo")
|
||||||
|
}
|
||||||
|
|
||||||
func (_ CacheTests) GCsTheOldestItems() {
|
func (_ CacheTests) GCsTheOldestItems() {
|
||||||
cache := New(Configure().ItemsToPrune(10))
|
cache := New(Configure().ItemsToPrune(10))
|
||||||
for i := 0; i < 500; i++ {
|
for i := 0; i < 500; i++ {
|
||||||
|
Reference in New Issue
Block a user