Files
dev-service/pkg/cache/cache.go
itzaname fecfc520a8
Some checks failed
continuous-integration/drone/push Build is failing
Update package path
2025-06-22 12:43:19 -04:00

82 lines
2.2 KiB
Go

package cache
import (
"context"
"encoding/json"
"fmt"
"github.com/redis/go-redis/v9"
"time"
"git.itzana.me/StrafesNET/dev-service/pkg/model"
)
// Cache is a simple caching interface for Redis
type Cache struct {
client *redis.Client
prefix string
}
// NewCache creates a new Redis cache client
func NewCache(client *redis.Client, prefix string) *Cache {
return &Cache{
client: client,
prefix: prefix,
}
}
// GetApplicationByAPIKey retrieves an application from cache by API key
func (c *Cache) GetApplicationByAPIKey(ctx context.Context, apiKey string) (*model.ApplicationCache, error) {
key := c.getAppAPIKeyCache(apiKey)
val, err := c.client.Get(ctx, key).Result()
if err != nil {
if err == redis.Nil {
return nil, fmt.Errorf("application with API key %s not found in cache", apiKey)
}
return nil, fmt.Errorf("failed to get from cache: %w", err)
}
var app model.ApplicationCache
if err := json.Unmarshal([]byte(val), &app); err != nil {
return nil, fmt.Errorf("failed to unmarshal application: %w", err)
}
return &app, nil
}
// SetApplicationByAPIKey caches an application with the given API key and expiration
func (c *Cache) SetApplicationByAPIKey(ctx context.Context, app *model.ApplicationCache, expiration time.Duration) error {
if app == nil || app.APIKey == "" {
return fmt.Errorf("invalid application or missing API key")
}
key := c.getAppAPIKeyCache(app.APIKey)
data, err := json.Marshal(app)
if err != nil {
return fmt.Errorf("failed to marshal application: %w", err)
}
if err := c.client.Set(ctx, key, data, expiration).Err(); err != nil {
return fmt.Errorf("failed to set in cache: %w", err)
}
return nil
}
// DeleteApplicationByAPIKey removes an application from cache by API key
func (c *Cache) DeleteApplicationByAPIKey(ctx context.Context, apiKey string) error {
key := c.getAppAPIKeyCache(apiKey)
if err := c.client.Del(ctx, key).Err(); err != nil {
return fmt.Errorf("failed to delete from cache: %w", err)
}
return nil
}
// getAppAPIKeyCache generates the cache key for an application by API key
func (c *Cache) getAppAPIKeyCache(apiKey string) string {
return fmt.Sprintf("%s:app:apikey:%s", c.prefix, apiKey)
}