dumb/handlers/cache.go

41 lines
720 B
Go
Raw Normal View History

package handlers
import (
2024-03-06 12:01:04 +01:00
"context"
"encoding/json"
"time"
"github.com/allegro/bigcache/v3"
"github.com/rramiachraf/dumb/data"
)
2024-03-04 20:43:46 +01:00
type cachable interface {
2024-06-23 16:38:53 -06:00
data.Album | data.Song | data.Annotation | data.Artist | data.Article | []byte
2024-03-04 20:43:46 +01:00
}
2024-03-06 12:01:04 +01:00
var c, _ = bigcache.New(context.Background(), bigcache.DefaultConfig(time.Hour*24))
func setCache(key string, entry interface{}) error {
data, err := json.Marshal(&entry)
if err != nil {
return err
}
return c.Set(key, data)
}
2024-03-04 20:43:46 +01:00
func getCache[v cachable](key string) (v, error) {
var decoded v
data, err := c.Get(key)
if err != nil {
return decoded, err
}
if err = json.Unmarshal(data, &decoded); err != nil {
return decoded, err
}
return decoded, nil
}