Mensa-API/cache/cache.go

39 lines
716 B
Go
Raw Permalink Normal View History

2024-03-27 16:41:57 +00:00
package cache
import (
2024-09-15 19:39:17 +00:00
"errors"
2024-09-15 16:57:03 +00:00
"github.com/LeRoid-hub/Mensa-API/models"
2024-03-27 16:41:57 +00:00
)
2024-12-19 23:52:24 +00:00
var Cache = make(map[string]models.CacheItem[interface{}])
2024-09-15 16:57:03 +00:00
func HasCacheData(key string) bool {
2024-09-16 16:29:34 +00:00
data, ok := Cache[key]
if !ok {
return false
}
if data.IsExpired() {
delete(Cache, key)
return false
}
2024-09-15 16:57:03 +00:00
return ok
2024-03-27 16:41:57 +00:00
}
2024-12-19 23:52:24 +00:00
func GetCacheData(key string) (interface{}, error) {
2024-09-15 16:57:03 +00:00
Item, ok := Cache[key]
if !ok {
2024-09-15 19:39:17 +00:00
return models.Mensa{}, errors.New("no data in cache")
2024-09-15 16:57:03 +00:00
}
return Item.GetData()
2024-03-27 16:41:57 +00:00
}
2024-12-19 23:52:24 +00:00
func SetCacheData(key string, data interface{}, lifetime ...int64) {
2024-09-15 16:57:03 +00:00
Item, ok := Cache[key]
if !ok {
2024-12-19 23:52:24 +00:00
Item = models.CacheItem[interface{}]{}
2024-09-15 16:57:03 +00:00
}
Item.SetData(data, lifetime...)
Cache[key] = Item
2024-03-27 16:41:57 +00:00
}