From 6a0ecc0fdceac4b1885f5072ae8b8c8aab773103 Mon Sep 17 00:00:00 2001 From: Robert Kopaczewski Date: Mon, 17 Aug 2020 21:32:09 +0200 Subject: [PATCH] feat: add store nil option to rediscache --- rediscache/cache.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/rediscache/cache.go b/rediscache/cache.go index 54c2346..b6256b0 100644 --- a/rediscache/cache.go +++ b/rediscache/cache.go @@ -1,6 +1,7 @@ package rediscache import ( + "errors" "reflect" "time" @@ -16,6 +17,10 @@ const ( versionGraceDuration = 5 * time.Minute ) +var ( + ErrNil = errors.New("compute returned nil object and storeNil is false") +) + type Cache struct { codec *cache.Codec db *database.DB @@ -27,6 +32,7 @@ type Config struct { CacheTimeout time.Duration CacheVersion int ServiceKey string + StoreNil bool } var DefaultConfig = Config{ @@ -34,6 +40,7 @@ var DefaultConfig = Config{ CacheTimeout: 12 * time.Hour, LocalCacheTimeout: 1 * time.Hour, ServiceKey: "cache", + StoreNil: false, } func WithTimeout(local, global time.Duration) func(*Config) { @@ -55,6 +62,12 @@ func WithServiceKey(val string) func(*Config) { } } +func WithStoreNil(storeNil bool) func(*Config) { + return func(config *Config) { + config.StoreNil = storeNil + } +} + // Init sets up a cache. func New(r rediser, db *database.DB, opts ...func(*Config)) *Cache { cfg := DefaultConfig @@ -126,6 +139,10 @@ func (c *Cache) VersionedCache(cacheKey, lookup string, val interface{}, return err } + if object == nil && !c.cfg.StoreNil { + return ErrNil + } + if version == "" { version, err = c.codec.Redis.Get(versionKeyFunc()).Result() if err != nil && err != redis.Nil {