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:
parent
ba1a063e86
commit
a8bc1b15a4
4 changed files with 80 additions and 0 deletions
37
util/linkpreview/cache.go
Normal file
37
util/linkpreview/cache.go
Normal 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
|
||||
}
|
40
util/linkpreview/cache_test.go
Normal file
40
util/linkpreview/cache_test.go
Normal 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)
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue