2023-05-23 18:44:05 -04:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/dgraph-io/badger/v2"
|
2023-08-14 18:16:42 -04:00
|
|
|
"go.fifitido.net/ytdl-web/pkg/ytdl/metadata"
|
2023-05-23 18:44:05 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
type MetadataCache interface {
|
|
|
|
Get(key string) (*metadata.Metadata, error)
|
|
|
|
Set(key string, value *metadata.Metadata, ttl time.Duration) error
|
|
|
|
}
|
|
|
|
|
|
|
|
type DefaultMetadataCache struct {
|
|
|
|
db *badger.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewDefaultMetadataCache(db *badger.DB) *DefaultMetadataCache {
|
|
|
|
return &DefaultMetadataCache{
|
|
|
|
db: db,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
func (c *DefaultMetadataCache) Get(key string) (*metadata.Metadata, error) {
|
|
|
|
value := &metadata.Metadata{}
|
|
|
|
err := c.db.View(func(txn *badger.Txn) error {
|
|
|
|
item, err := txn.Get([]byte(key))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return item.Value(func(val []byte) error {
|
|
|
|
return json.Unmarshal(val, value)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
return value, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *DefaultMetadataCache) Set(key string, value *metadata.Metadata, ttl time.Duration) error {
|
|
|
|
return c.db.Update(func(txn *badger.Txn) error {
|
|
|
|
data, err := json.Marshal(value)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
e := badger.NewEntry([]byte(key), data).WithTTL(ttl)
|
|
|
|
return txn.SetEntry(e)
|
|
|
|
})
|
|
|
|
}
|