Skip to content

Commit

Permalink
feat: add onlyUpdateCache option
Browse files Browse the repository at this point in the history
  • Loading branch information
tw7613781 committed Dec 29, 2023
1 parent 83df4de commit b6d3788
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
8 changes: 5 additions & 3 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,11 @@ func cache(
respCache := &ResponseCache{}
err := cacheStore.Get(cacheKey, &respCache)
if err == nil {
replyWithCache(c, cfg, respCache)
cfg.hitCacheCallback(c)
return
if !cfg.onlyUpdateCache {
replyWithCache(c, cfg, respCache)
cfg.hitCacheCallback(c)
return
}
}

if err != persist.ErrCacheMiss {
Expand Down
18 changes: 18 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,24 @@ func TestCacheByRequestURIIgnoreOrder(t *testing.T) {
assert.NotEqual(t, w3.Body, w1.Body)
}

func TestCacheByRequestURIOnlyUpdateCache(t *testing.T) {
memoryStore := persist.NewMemoryStore(1 * time.Minute)
cacheURIMiddleware := CacheByRequestURI(memoryStore, 3*time.Second)

w1 := mockHttpRequest(cacheURIMiddleware, "/cache?uid=u1", true)
w2 := mockHttpRequest(cacheURIMiddleware, "/cache?uid=u1", true)
assert.Equal(t, w1.Body, w2.Body)

cacheURIMiddlewareOnlyUpdateCache := CacheByRequestURI(memoryStore, 3*time.Second, OnlyUpdateCache())

w3 := mockHttpRequest(cacheURIMiddlewareOnlyUpdateCache, "/cache?uid=u1", true)
w4 := mockHttpRequest(cacheURIMiddlewareOnlyUpdateCache, "/cache?uid=u1", true)
assert.NotEqual(t, w3.Body, w4.Body)

w5 := mockHttpRequest(cacheURIMiddleware, "/cache?uid=u1", true)
assert.Equal(t, w5.Body, w4.Body)
}

const prefixKey = "#prefix#"

func TestPrefixKey(t *testing.T) {
Expand Down
7 changes: 7 additions & 0 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type Config struct {
prefixKey string
withoutHeader bool
discardHeaders []string
onlyUpdateCache bool
}

func newConfigByOpts(opts ...Option) *Config {
Expand Down Expand Up @@ -148,6 +149,12 @@ func IgnoreQueryOrder() Option {
}
}

func OnlyUpdateCache() Option {
return func(c *Config) {
c.onlyUpdateCache = true
}
}

// WithPrefixKey will prefix the key
func WithPrefixKey(prefix string) Option {
return func(c *Config) {
Expand Down

0 comments on commit b6d3788

Please sign in to comment.