From 746ba073abfbb3221958a028bf6a31e0ba7c4b9c Mon Sep 17 00:00:00 2001 From: jano3 <jano@bob.co.za> Date: Thu, 6 Jun 2024 10:45:30 +0200 Subject: [PATCH] Allow updating redis key expiry when getting values --- redis/redis.go | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/redis/redis.go b/redis/redis.go index a28528b..cb305b8 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 */ -- GitLab