1
0
Fork 0
mirror of https://github.com/anyproto/anytype-heart.git synced 2025-06-10 18:10:49 +09:00
anytype-heart/util/linkpreview/cache.go
2023-04-25 18:17:59 +02:00

44 lines
749 B
Go

package linkpreview
import (
"context"
"github.com/golang/groupcache/lru"
"github.com/anytypeio/any-sync/app"
"github.com/anytypeio/go-anytype-middleware/pkg/lib/pb/model"
)
const (
maxCacheEntries = 100
)
func NewWithCache() LinkPreview {
return &cache{}
}
type cache struct {
lp LinkPreview
cache *lru.Cache
}
func (c *cache) Init(_ *app.App) (err error) {
c.lp = New()
c.cache = lru.New(maxCacheEntries)
return
}
func (c *cache) Name() string {
return CName
}
func (c *cache) Fetch(ctx context.Context, url string) (lp model.LinkPreview, err error) {
if res, ok := c.cache.Get(url); ok {
return res.(model.LinkPreview), nil
}
lp, err = c.lp.Fetch(ctx, url)
if err != nil {
return
}
c.cache.Add(url, lp)
return
}