Initial Commit of Redis Plugin with Unit Test cases
This commit is contained in:
32
pkg/plugin/implementation/cache/cache.go
vendored
32
pkg/plugin/implementation/cache/cache.go
vendored
@@ -10,6 +10,9 @@ import (
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// Global variable for the Redis client, can be overridden in tests
|
||||
var RedisCl *redis.Client
|
||||
|
||||
// RedisClient is an interface for Redis operations that allows mocking
|
||||
type RedisClient interface {
|
||||
Get(ctx context.Context, key string) *redis.StringCmd
|
||||
@@ -17,6 +20,7 @@ type RedisClient interface {
|
||||
Del(ctx context.Context, keys ...string) *redis.IntCmd
|
||||
FlushDB(ctx context.Context) *redis.StatusCmd
|
||||
Ping(ctx context.Context) *redis.StatusCmd
|
||||
Close() error
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
@@ -24,7 +28,7 @@ type Config struct {
|
||||
}
|
||||
|
||||
type Cache struct {
|
||||
client RedisClient
|
||||
Client RedisClient
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -44,38 +48,40 @@ func validate(cfg *Config) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
var RedisClientFunc = func(cfg *Config) RedisClient {
|
||||
return redis.NewClient(&redis.Options{
|
||||
Addr: cfg.Addr,
|
||||
Password: os.Getenv("REDIS_PASSWORD"),
|
||||
DB: 0,
|
||||
})
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg *Config) (*Cache, func() error, error) {
|
||||
if err := validate(cfg); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
password := os.Getenv("REDIS_PASSWORD")
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: cfg.Addr,
|
||||
Password: password,
|
||||
DB: 0, // Always use default DB 0
|
||||
})
|
||||
client := RedisClientFunc(cfg)
|
||||
|
||||
if _, err := client.Ping(ctx).Result(); err != nil {
|
||||
return nil, nil, fmt.Errorf("%w: %v", ErrConnectionFail, err)
|
||||
}
|
||||
|
||||
return &Cache{client: client}, client.Close, nil
|
||||
return &Cache{Client: client}, client.Close, nil
|
||||
}
|
||||
|
||||
func (c *Cache) Get(ctx context.Context, key string) (string, error) {
|
||||
return c.client.Get(ctx, key).Result()
|
||||
return c.Client.Get(ctx, key).Result()
|
||||
}
|
||||
|
||||
func (c *Cache) Set(ctx context.Context, key, value string, ttl time.Duration) error {
|
||||
return c.client.Set(ctx, key, value, ttl).Err()
|
||||
return c.Client.Set(ctx, key, value, ttl).Err()
|
||||
}
|
||||
|
||||
func (c *Cache) Delete(ctx context.Context, key string) error {
|
||||
return c.client.Del(ctx, key).Err()
|
||||
return c.Client.Del(ctx, key).Err()
|
||||
}
|
||||
|
||||
func (c *Cache) Clear(ctx context.Context) error {
|
||||
return c.client.FlushDB(ctx).Err()
|
||||
return c.Client.FlushDB(ctx).Err()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user