Mensa-API/models/cacheItem.go

36 lines
583 B
Go
Raw Normal View History

2024-09-15 16:57:03 +00:00
package models
2024-09-15 19:39:17 +00:00
import (
"errors"
"time"
)
2024-09-15 16:57:03 +00:00
type CacheItem struct {
2024-09-15 19:39:17 +00:00
data Mensa
2024-09-15 16:57:03 +00:00
lastUpdated time.Time
lifetime int64
}
2024-09-15 19:39:17 +00:00
func (c *CacheItem) SetData(data Mensa, lifetime ...int64) {
2024-09-15 16:57:03 +00:00
if len(lifetime) > 0 {
c.lifetime = lifetime[0]
} else {
c.lifetime = 60
}
c.data = data
c.lastUpdated = time.Now()
}
2024-09-15 19:39:17 +00:00
func (c *CacheItem) GetData() (Mensa, error) {
2024-09-15 16:57:03 +00:00
if time.Now().Unix()-c.lastUpdated.Unix() > c.lifetime {
2024-09-15 19:39:17 +00:00
return Mensa{}, errors.New("cache expired")
2024-09-15 16:57:03 +00:00
}
2024-09-15 19:39:17 +00:00
if c.lastUpdated.IsZero() {
return Mensa{}, errors.New("no data in cache")
2024-09-15 16:57:03 +00:00
}
2024-09-15 19:39:17 +00:00
return c.data, nil
2024-09-15 16:57:03 +00:00
}