Mensa-API/models/cacheItem.go

45 lines
802 B
Go
Raw Permalink Normal View History

2024-09-20 21:18:45 +00:00
package models
import (
"errors"
"time"
)
2024-12-19 23:52:24 +00:00
type CacheItem[C any] struct {
data C
2024-09-20 21:18:45 +00:00
lastUpdated time.Time
lifetime int64
}
2024-12-19 23:52:24 +00:00
func (c *CacheItem[C]) SetData(data C, lifetime ...int64) {
2024-09-20 21:18:45 +00:00
if len(lifetime) > 0 {
c.lifetime = lifetime[0]
} else {
c.lifetime = 60
}
c.data = data
c.lastUpdated = time.Now()
}
2024-12-19 23:52:24 +00:00
func (c *CacheItem[C]) GetData() (C, error) {
2024-09-20 21:18:45 +00:00
if time.Now().Unix()-c.lastUpdated.Unix() > c.lifetime {
2024-12-19 23:52:24 +00:00
var zeroValue C
return zeroValue, errors.New("cache expired")
2024-09-20 21:18:45 +00:00
}
if c.lastUpdated.IsZero() {
2024-12-19 23:52:24 +00:00
var zeroValue C
return zeroValue, errors.New("no data in cache")
2024-09-20 21:18:45 +00:00
}
return c.data, nil
}
2024-12-19 23:52:24 +00:00
func (c *CacheItem[C]) IsExpired() bool {
2024-09-20 21:18:45 +00:00
if time.Now().Unix()-c.lastUpdated.Unix() > c.lifetime {
return true
}
return false
}