s3browser-backend/internal/cache/ttl_cache.go
2021-10-14 19:00:11 +02:00

45 lines
859 B
Go

package cache
import (
"context"
"time"
"github.com/graph-gophers/dataloader"
gocache "github.com/patrickmn/go-cache"
)
type TTLCache struct {
c *gocache.Cache
}
// Create new ttl cache
func NewTTLCache(ttl, cleanupInterval time.Duration) *TTLCache {
return &TTLCache{
c: gocache.New(ttl, cleanupInterval),
}
}
func (c *TTLCache) Get(_ context.Context, key dataloader.Key) (dataloader.Thunk, bool) {
v, ok := c.c.Get(key.String())
if ok {
return v.(dataloader.Thunk), ok
}
return nil, ok
}
func (c *TTLCache) Set(_ context.Context, key dataloader.Key, value dataloader.Thunk) {
c.c.Set(key.String(), value, 0)
}
func (c *TTLCache) Delete(_ context.Context, key dataloader.Key) bool {
if _, found := c.c.Get(key.String()); found {
c.c.Delete(key.String())
return true
}
return false
}
func (c *TTLCache) Clear() {
c.c.Flush()
}