Skip to content
Snippets Groups Projects
Commit 746ba073 authored by Jano Hendriks's avatar Jano Hendriks
Browse files

Allow updating redis key expiry when getting values

parent a1f9cdfe
Branches
Tags v1.225.0
No related merge requests found
...@@ -184,14 +184,16 @@ func (r ClientWithHelpers) SetObjectByKeyIndefinitely(key string, object interfa ...@@ -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 // Make sure we have a Redis client, and it is connected
if redisClient == nil || !redisClient.IsConnected() { if redisClient == nil || !redisClient.IsConnected() {
return nil return nil
} }
// Get the object from Redis // Get the object from Redis
jsonString := redisClient.GetValueByKey(key) jsonString := redisClient.GetValueByKey(key, expiry...)
if jsonString == "" { if jsonString == "" {
return nil return nil
} }
...@@ -205,12 +207,20 @@ func GetObjectByKey[T any](redisClient *ClientWithHelpers, key string, object T) ...@@ -205,12 +207,20 @@ func GetObjectByKey[T any](redisClient *ClientWithHelpers, key string, object T)
return &object 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() { if !r.IsConnected() {
return "" 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 */ if err == redis.Nil { /* Key does not exist */
return "" return ""
} else if err != nil { /* Actual error */ } else if err != nil { /* Actual error */
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment