From b3128a292ca6b3c4b9b61c36129ff4c022104447 Mon Sep 17 00:00:00 2001 From: fajrifernanda Date: Tue, 13 May 2025 10:01:03 +0700 Subject: [PATCH] feature: add StoreCachesWithCustomTTL --- common.go | 31 +++++++++++++++++++++++++++++++ keeper.go | 2 +- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/common.go b/common.go index ca78879..ca57632 100644 --- a/common.go +++ b/common.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "strconv" + "time" "github.com/kumparan/go-utils" "github.com/sirupsen/logrus" @@ -165,3 +166,33 @@ func StoreCaches[K comparable, V any](cacheKeeper Keeper, keys []K, buffer map[K logger.WithField("cacheItems", utils.Dump(cacheItems)).Error(err) } } + +// StoreCachesWithCustomTTL store multiple object by keys with custom ttl +func StoreCachesWithCustomTTL[K comparable, V any](cacheKeeper Keeper, keys []K, buffer map[K]V, cacheKeyFunc func(K) string, ttl time.Duration) { + logger := logrus.WithFields(logrus.Fields{ + "keys": keys, + "buffer": utils.Dump(buffer), + }) + + var cacheItems []Item + for _, key := range keys { + val, ok := buffer[key] + if !ok { + cacheItems = append(cacheItems, NewItem(cacheKeyFunc(key), []byte("null"))) + continue + } + + jsonVal, err := json.Marshal(val) + if err != nil { + logger.WithField("key", key).Error(err) + continue + } + + cacheItems = append(cacheItems, NewItemWithCustomTTL(cacheKeyFunc(key), jsonVal, ttl)) + } + + err := cacheKeeper.StoreMultiWithoutBlocking(cacheItems) + if err != nil { + logger.WithField("cacheItems", utils.Dump(cacheItems)).Error(err) + } +} diff --git a/keeper.go b/keeper.go index d44ff27..dbc29f3 100644 --- a/keeper.go +++ b/keeper.go @@ -71,7 +71,7 @@ type ( CheckKeyExist(string) (bool, error) - //list + // list StoreRightList(string, any) error StoreLeftList(string, any) error GetList(string, int64, int64) (any, error)