diff --git a/redis/redis.go b/redis/redis.go index a28528ba0868b985b8de449bb63ab1d87799a34e..cb305b8801abe4b3df18ecf5d789cfb5ca58396c 100644 --- a/redis/redis.go +++ b/redis/redis.go @@ -184,14 +184,16 @@ func (r ClientWithHelpers) SetObjectByKeyIndefinitely(key string, object interfa } -func GetObjectByKey[T any](redisClient *ClientWithHelpers, key string, object T) *T { +// GetObjectByKey fetches an object from Redis by key. If the key does not exist or there is an error, it returns nil. +// If an expiry is provided, it will both fetch the key and update its expiry. +func GetObjectByKey[T any](redisClient *ClientWithHelpers, key string, object T, expiry ...time.Duration) *T { // Make sure we have a Redis client, and it is connected if redisClient == nil || !redisClient.IsConnected() { return nil } // Get the object from Redis - jsonString := redisClient.GetValueByKey(key) + jsonString := redisClient.GetValueByKey(key, expiry...) if jsonString == "" { return nil } @@ -205,12 +207,20 @@ func GetObjectByKey[T any](redisClient *ClientWithHelpers, key string, object T) return &object } -func (r ClientWithHelpers) GetValueByKey(key string) string { +// GetValueByKey fetches a value from Redis by key. If the key does not exist or there is an error, it returns an empty +// string. If an expiry is provided, it will both fetch the key and update its expiry. +func (r ClientWithHelpers) GetValueByKey(key string, expiry ...time.Duration) string { if !r.IsConnected() { return "" } - jsonString, err := r.Client.Get(ctx, key).Result() + var jsonString string + var err error + if len(expiry) > 0 { + jsonString, err = r.Client.GetEx(ctx, key, expiry[0]).Result() + } else { + jsonString, err = r.Client.Get(ctx, key).Result() + } if err == redis.Nil { /* Key does not exist */ return "" } else if err != nil { /* Actual error */