s3browser-backend/internal/cache/ttl_cache.go

45 lines
859 B
Go
Raw Normal View History

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