diff --git a/cache.go b/cache.go index 5f8d127..c5bb08a 100644 --- a/cache.go +++ b/cache.go @@ -9,6 +9,15 @@ import ( type replaceFunc[K comparable, V any] func(ctx context.Context, key K) (V, error) +// NewMust is similar to New, but panics on error. +func NewMust[K comparable, V any](replaceFn replaceFunc[K, V], freshFor, ttl time.Duration, options ...CacheOption) *Cache[K, V] { + c, err := New(replaceFn, freshFor, ttl, options...) + if err != nil { + panic(err) + } + return c +} + // New creates a new cache instance. // You can specify ttl longer than freshFor to achieve 'graceful cache replacement', where stale item is served via Get // while a single goroutine is launched in the background to retrieve a fresh item. diff --git a/cache_test.go b/cache_test.go index 211b0ff..861afaa 100644 --- a/cache_test.go +++ b/cache_test.go @@ -12,7 +12,30 @@ import ( "github.com/stretchr/testify/assert" ) -// TestNew tests the behavior of New. +func TestNewMust(t *testing.T) { + t.Parallel() + + fn := func(ctx context.Context, s string) (string, error) { return "", nil } + + t.Run("success", func(t *testing.T) { + t.Parallel() + + _ = NewMust(fn, 0, 0) + }) + t.Run("fail", func(t *testing.T) { + t.Parallel() + + func() { + defer func() { + err := recover() + assert.NotNil(t, err) + }() + + _ = NewMust(fn, -1, -1) + }() + }) +} + func TestNew(t *testing.T) { t.Parallel()