Added custom cache client for much easier cache operations.

This commit is contained in:
mikestefanello 2022-01-13 21:13:41 -05:00
parent d412e06dad
commit bfbb9669aa
8 changed files with 451 additions and 64 deletions

105
services/cache_test.go Normal file
View file

@ -0,0 +1,105 @@
package services
import (
"context"
"testing"
"time"
"github.com/go-redis/redis/v8"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCacheClient(t *testing.T) {
type cacheTest struct {
Value string
}
// Cache some data
data := cacheTest{Value: "abcdef"}
group := "testgroup"
key := "testkey"
err := c.Cache.
Set().
Group(group).
Key(key).
Data(data).
Save(context.Background())
require.NoError(t, err)
// Get the data
fromCache, err := c.Cache.
Get().
Group(group).
Key(key).
Type(new(cacheTest)).
Fetch(context.Background())
require.NoError(t, err)
cast, ok := fromCache.(*cacheTest)
require.True(t, ok)
assert.Equal(t, data, *cast)
// The same key with the wrong group should fail
_, err = c.Cache.
Get().
Key(key).
Type(new(cacheTest)).
Fetch(context.Background())
assert.Error(t, err)
// Flush the data
err = c.Cache.
Flush().
Group(group).
Key(key).
Exec(context.Background())
require.NoError(t, err)
// The data should be gone
assertFlushed := func() {
// The data should be gone
_, err = c.Cache.
Get().
Group(group).
Key(key).
Type(new(cacheTest)).
Fetch(context.Background())
assert.Equal(t, redis.Nil, err)
}
assertFlushed()
// Set with tags
err = c.Cache.
Set().
Group(group).
Key(key).
Data(data).
Tags([]string{"tag1"}).
Save(context.Background())
require.NoError(t, err)
// Flush the tag
err = c.Cache.
Flush().
Tags([]string{"tag1"}).
Exec(context.Background())
require.NoError(t, err)
// The data should be gone
assertFlushed()
// Set with expiration
err = c.Cache.
Set().
Group(group).
Key(key).
Data(data).
Expiration(time.Millisecond).
Save(context.Background())
require.NoError(t, err)
// Wait for expiration
time.Sleep(time.Millisecond * 2)
// The data should be gone
assertFlushed()
}