1
0
Fork 0
mirror of https://github.com/anyproto/anytype-heart.git synced 2025-06-10 18:10:49 +09:00

linkPreview cache

This commit is contained in:
Sergey Cherepanov 2020-02-13 20:45:21 +03:00
parent ba1a063e86
commit a8bc1b15a4
No known key found for this signature in database
GPG key ID: 085319C64294F576
4 changed files with 80 additions and 0 deletions

37
util/linkpreview/cache.go Normal file
View file

@ -0,0 +1,37 @@
package linkpreview
import (
"context"
"github.com/anytypeio/go-anytype-library/pb/model"
"github.com/hashicorp/golang-lru"
)
const (
maxCacheEntries = 100
)
func NewWithCache() LinkPreview {
lruCache, _ := lru.New(maxCacheEntries)
return &cache{
lp: New(),
cache: lruCache,
}
}
type cache struct {
lp LinkPreview
cache *lru.Cache
}
func (c *cache) Fetch(ctx context.Context, url string) (lp model.ModelLinkPreview, err error) {
if res, ok := c.cache.Get(url); ok {
return res.(model.ModelLinkPreview), nil
}
lp, err = c.lp.Fetch(ctx, url)
if err != nil {
return
}
c.cache.Add(url, lp)
return
}

View file

@ -0,0 +1,40 @@
package linkpreview
import (
"strings"
"testing"
"github.com/anytypeio/go-anytype-library/pb/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCache_Fetch(t *testing.T) {
ts := newTestServer("text/html", strings.NewReader(tetsHtml))
lp := NewWithCache()
info, err := lp.Fetch(ctx, ts.URL)
require.NoError(t, err)
assert.Equal(t, model.ModelLinkPreview{
Url: ts.URL,
FaviconUrl: ts.URL + "/favicon.ico",
Title: "Title",
Description: "Description",
ImageUrl: "http://site.com/images/example.jpg",
Type: model.ModelLinkPreview_Page,
}, info)
ts.Close()
info, err = lp.Fetch(ctx, ts.URL)
require.NoError(t, err)
assert.Equal(t, model.ModelLinkPreview{
Url: ts.URL,
FaviconUrl: ts.URL + "/favicon.ico",
Title: "Title",
Description: "Description",
ImageUrl: "http://site.com/images/example.jpg",
Type: model.ModelLinkPreview_Page,
}, info)
}