saasitone/pkg/handlers/cache.go

94 lines
1.9 KiB
Go
Raw Permalink Normal View History

package handlers
import (
"errors"
"time"
2024-07-09 17:57:05 -07:00
"github.com/labstack/echo/v4"
"git.grosinger.net/tgrosinger/saasitone/pkg/form"
"git.grosinger.net/tgrosinger/saasitone/pkg/page"
"git.grosinger.net/tgrosinger/saasitone/pkg/services"
2024-07-17 20:10:04 -07:00
"git.grosinger.net/tgrosinger/saasitone/templ/layouts"
"git.grosinger.net/tgrosinger/saasitone/templ/pages"
)
const (
routeNameCache = "cache"
routeNameCacheSubmit = "cache.submit"
)
type (
Cache struct {
cache *services.CacheClient
*services.TemplateRenderer
}
)
func init() {
Register(new(Cache))
}
func (h *Cache) Init(c *services.Container) error {
h.TemplateRenderer = c.TemplateRenderer
h.cache = c.Cache
return nil
}
func (h *Cache) Routes(g *echo.Group) {
g.GET("/cache", h.Page).Name = routeNameCache
g.POST("/cache", h.Submit).Name = routeNameCacheSubmit
}
func (h *Cache) Page(ctx echo.Context) error {
p := page.New(ctx)
p.Title = "Set a cache entry"
p.LayoutComponent = layouts.Main
// Fetch the value from the cache
value, err := h.cache.
Get().
Key("page_cache_example").
Fetch(ctx.Request().Context())
2024-07-17 20:10:04 -07:00
var valueStrPtr *string = nil
// Store the value in the page, so it can be rendered, if found
switch {
case err == nil:
2024-07-17 20:10:04 -07:00
valueStr := value.(string)
valueStrPtr = &valueStr
case errors.Is(err, services.ErrCacheMiss):
default:
return fail(err, "failed to fetch from cache")
}
2024-07-17 20:10:04 -07:00
f := form.Get[pages.CacheForm](ctx)
component := pages.Cache(p, f, valueStrPtr)
return h.RenderPageTempl(ctx, p, component)
}
func (h *Cache) Submit(ctx echo.Context) error {
2024-07-17 20:10:04 -07:00
var input pages.CacheForm
if err := form.Submit(ctx, &input); err != nil {
return err
}
// Set the cache
err := h.cache.
Set().
Key("page_cache_example").
Data(input.Value).
Expiration(30 * time.Minute).
Save(ctx.Request().Context())
if err != nil {
return fail(err, "unable to set cache")
}
form.Clear(ctx)
return h.Page(ctx)
}