Generic Cache

This commit is contained in:
Jan Barfuss 2024-12-20 00:52:24 +01:00
parent 08bd2d8df8
commit 9e27e076a0
4 changed files with 165 additions and 163 deletions

8
cache/cache.go vendored
View File

@ -6,7 +6,7 @@ import (
"github.com/LeRoid-hub/Mensa-API/models"
)
var Cache = make(map[string]models.CacheItem)
var Cache = make(map[string]models.CacheItem[interface{}])
func HasCacheData(key string) bool {
data, ok := Cache[key]
@ -20,7 +20,7 @@ func HasCacheData(key string) bool {
return ok
}
func GetCacheData(key string) (models.Mensa, error) {
func GetCacheData(key string) (interface{}, error) {
Item, ok := Cache[key]
if !ok {
return models.Mensa{}, errors.New("no data in cache")
@ -28,10 +28,10 @@ func GetCacheData(key string) (models.Mensa, error) {
return Item.GetData()
}
func SetCacheData(key string, data models.Mensa, lifetime ...int64) {
func SetCacheData(key string, data interface{}, lifetime ...int64) {
Item, ok := Cache[key]
if !ok {
Item = models.CacheItem{}
Item = models.CacheItem[interface{}]{}
}
Item.SetData(data, lifetime...)
Cache[key] = Item

View File

@ -5,13 +5,13 @@ import (
"time"
)
type CacheItem struct {
data Mensa
type CacheItem[C any] struct {
data C
lastUpdated time.Time
lifetime int64
}
func (c *CacheItem) SetData(data Mensa, lifetime ...int64) {
func (c *CacheItem[C]) SetData(data C, lifetime ...int64) {
if len(lifetime) > 0 {
c.lifetime = lifetime[0]
} else {
@ -22,19 +22,21 @@ func (c *CacheItem) SetData(data Mensa, lifetime ...int64) {
c.lastUpdated = time.Now()
}
func (c *CacheItem) GetData() (Mensa, error) {
func (c *CacheItem[C]) GetData() (C, error) {
if time.Now().Unix()-c.lastUpdated.Unix() > c.lifetime {
return Mensa{}, errors.New("cache expired")
var zeroValue C
return zeroValue, errors.New("cache expired")
}
if c.lastUpdated.IsZero() {
return Mensa{}, errors.New("no data in cache")
var zeroValue C
return zeroValue, errors.New("no data in cache")
}
return c.data, nil
}
func (c *CacheItem) IsExpired() bool {
func (c *CacheItem[C]) IsExpired() bool {
if time.Now().Unix()-c.lastUpdated.Unix() > c.lifetime {
return true
}