mirror of
https://github.com/LeRoid-hub/Mensa-API.git
synced 2025-01-31 03:34:57 +00:00
Generic Cache
This commit is contained in:
parent
08bd2d8df8
commit
9e27e076a0
8
cache/cache.go
vendored
8
cache/cache.go
vendored
@ -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
|
||||
|
@ -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
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user