Skip to content

Commit

Permalink
feat: add store nil option to rediscache
Browse files Browse the repository at this point in the history
  • Loading branch information
23doors committed Aug 17, 2020
1 parent ff68e9e commit 6a0ecc0
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions rediscache/cache.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package rediscache

import (
"errors"
"reflect"
"time"

Expand All @@ -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
Expand All @@ -27,13 +32,15 @@ type Config struct {
CacheTimeout time.Duration
CacheVersion int
ServiceKey string
StoreNil bool
}

var DefaultConfig = Config{
CacheVersion: 1,
CacheTimeout: 12 * time.Hour,
LocalCacheTimeout: 1 * time.Hour,
ServiceKey: "cache",
StoreNil: false,
}

func WithTimeout(local, global time.Duration) func(*Config) {
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 6a0ecc0

Please sign in to comment.