Added custom cache client for much easier cache operations.

This commit is contained in:
mikestefanello 2022-01-13 21:13:41 -05:00
parent d412e06dad
commit bfbb9669aa
8 changed files with 451 additions and 64 deletions

View file

@ -9,10 +9,6 @@ import (
"github.com/mikestefanello/pagoda/middleware"
"github.com/mikestefanello/pagoda/services"
"github.com/eko/gocache/v2/marshaler"
"github.com/eko/gocache/v2/store"
"github.com/labstack/echo/v4"
)
@ -131,10 +127,6 @@ func (c *Controller) cachePage(ctx echo.Context, page Page, html *bytes.Buffer)
// The request URL is used as the cache key so the middleware can serve the
// cached page on matching requests
key := ctx.Request().URL.String()
opts := &store.Options{
Expiration: page.Cache.Expiration,
Tags: page.Cache.Tags,
}
cp := middleware.CachedPage{
URL: key,
HTML: html.Bytes(),
@ -142,16 +134,21 @@ func (c *Controller) cachePage(ctx echo.Context, page Page, html *bytes.Buffer)
StatusCode: ctx.Response().Status,
}
err := marshaler.New(c.Container.Cache).Set(ctx.Request().Context(), key, cp, opts)
if err != nil {
if !context.IsCanceledError(err) {
ctx.Logger().Errorf("failed to cache page: %v", err)
}
err := c.Container.Cache.
Set().
Group(middleware.CachedPageGroup).
Key(key).
Tags(page.Cache.Tags).
Expiration(page.Cache.Expiration).
Data(cp).
Save(ctx.Request().Context())
return
switch {
case err == nil:
ctx.Logger().Info("cached page")
case !context.IsCanceledError(err):
ctx.Logger().Errorf("failed to cache page: %v", err)
}
ctx.Logger().Infof("cached page")
}
// Redirect redirects to a given route name with optional route parameters

View file

@ -14,10 +14,6 @@ import (
"github.com/mikestefanello/pagoda/services"
"github.com/mikestefanello/pagoda/tests"
"github.com/eko/gocache/v2/store"
"github.com/eko/gocache/v2/marshaler"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@ -151,8 +147,12 @@ func TestController_RenderPage(t *testing.T) {
require.NoError(t, err)
// Fetch from the cache
res, err := marshaler.New(c.Cache).
Get(context.Background(), p.URL, new(middleware.CachedPage))
res, err := c.Cache.
Get().
Group(middleware.CachedPageGroup).
Key(p.URL).
Type(new(middleware.CachedPage)).
Fetch(context.Background())
require.NoError(t, err)
// Compare the cached page
@ -164,14 +164,19 @@ func TestController_RenderPage(t *testing.T) {
assert.Equal(t, rec.Body.Bytes(), cp.HTML)
// Clear the tag
err = c.Cache.Invalidate(context.Background(), store.InvalidateOptions{
Tags: []string{p.Cache.Tags[0]},
})
err = c.Cache.
Flush().
Tags([]string{p.Cache.Tags[0]}).
Exec(context.Background())
require.NoError(t, err)
// Refetch from the cache and expect no results
_, err = marshaler.New(c.Cache).
Get(context.Background(), p.URL, new(middleware.CachedPage))
_, err = c.Cache.
Get().
Group(middleware.CachedPageGroup).
Key(p.URL).
Type(new(middleware.CachedPage)).
Fetch(context.Background())
assert.Error(t, err)
})
}