Skip to content

Commit

Permalink
add cache repository
Browse files Browse the repository at this point in the history
  • Loading branch information
Poby Zaarifwandono committed Aug 14, 2024
1 parent d85e00d commit 07750ba
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 2 deletions.
8 changes: 6 additions & 2 deletions redis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cache_test
import (
"context"
"log"
"os"
"testing"
"time"

Expand All @@ -25,8 +26,11 @@ func TestRedisCache(t *testing.T) {
}

// Create a new Redis client
url := "redis://localhost:6379/0?protocol=3"
opts, err := redis.ParseURL(url)
redisURL := os.Getenv("GOCACHE_REDIS_URL")
if redisURL == "" {
redisURL = "redis://localhost:6379/0?protocol=3"
}
opts, err := redis.ParseURL(redisURL)
if err != nil {
log.Fatalf("Could not connect to Redis: %v", err)
}
Expand Down
12 changes: 12 additions & 0 deletions repository.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package cache

import "time"

// Repository cache repository
type Repository interface {
Set(key string, value interface{}, expiration time.Duration) (err error)

Get(key string, data interface{}) (err error)

Delete(key string)
}
60 changes: 60 additions & 0 deletions repository_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package cache_test

import (
"context"
"log"
"os"
"testing"
"time"

cache "github.com/pobyzaarif/go-cache"
redis "github.com/redis/go-redis/v9"
"github.com/stretchr/testify/assert"
)

func TestRepositoryCache(t *testing.T) {
staging := true

var repo cache.Repository

if staging {
var errMemCache error
repo, errMemCache = cache.NewMemoryARCCacheRepository(15) // increase 1 the size to avoid overcapacity of the cache because lru, lfu, and arc will remove unpopular keys automatically based on each algorithm
assert.NoError(t, errMemCache)
} else {
// Create a new Redis client
redisURL := os.Getenv("GOCACHE_REDIS_URL")
if redisURL == "" {
redisURL = "redis://localhost:6379/0?protocol=3"
}
opts, err := redis.ParseURL(redisURL)
if err != nil {
log.Fatalf("Could not connect to Redis: %v", err)
}

rdb := redis.NewClient(opts)

// Ping the Redis server to check the connection
_, err = rdb.Ping(context.TODO()).Result()
if err != nil {
log.Fatalf("Could not connect to Redis: %v", err)
}

repo = cache.NewRedisCacheRepository(rdb)
}

var test int
err := repo.Set("test", 1, 5*time.Minute)
assert.NoError(t, err)

err = repo.Get("test", &test)
assert.NoError(t, err)
assert.Equal(t, 1, test)

repo.Delete("test")

var testB int
err = repo.Get("test", &testB)
assert.NoError(t, err)
assert.Equal(t, 0, testB)
}

0 comments on commit 07750ba

Please sign in to comment.