2024-06-22 07:34:26 -07:00
|
|
|
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"
|
2024-06-22 07:34:26 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
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"
|
2024-07-27 12:28:45 -07:00
|
|
|
p.LayoutComponent = layouts.Main
|
2024-06-22 07:34:26 -07:00
|
|
|
|
|
|
|
// 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
|
|
|
|
|
2024-06-22 07:34:26 -07:00
|
|
|
// 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
|
2024-06-22 07:34:26 -07:00
|
|
|
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)
|
2024-06-22 07:34:26 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Cache) Submit(ctx echo.Context) error {
|
2024-07-17 20:10:04 -07:00
|
|
|
var input pages.CacheForm
|
2024-06-22 07:34:26 -07:00
|
|
|
|
|
|
|
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)
|
|
|
|
}
|