Reorganized directories and packages.
This commit is contained in:
parent
1018d82d13
commit
72ce41c828
61 changed files with 83 additions and 83 deletions
171
pkg/controller/controller.go
Normal file
171
pkg/controller/controller.go
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
package controller
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/mikestefanello/pagoda/pkg/context"
|
||||
"github.com/mikestefanello/pagoda/pkg/htmx"
|
||||
"github.com/mikestefanello/pagoda/pkg/middleware"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
// Controller provides base functionality and dependencies to routes.
|
||||
// The proposed pattern is to embed a Controller in each individual route struct and to use
|
||||
// the router to inject the container so your routes have access to the services within the container
|
||||
type Controller struct {
|
||||
// Container stores a services container which contains dependencies
|
||||
Container *services.Container
|
||||
}
|
||||
|
||||
// NewController creates a new Controller
|
||||
func NewController(c *services.Container) Controller {
|
||||
return Controller{
|
||||
Container: c,
|
||||
}
|
||||
}
|
||||
|
||||
// RenderPage renders a Page as an HTTP response
|
||||
func (c *Controller) RenderPage(ctx echo.Context, page Page) error {
|
||||
var buf *bytes.Buffer
|
||||
var err error
|
||||
|
||||
// Page name is required
|
||||
if page.Name == "" {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, "page render failed due to missing name")
|
||||
}
|
||||
|
||||
// Use the app name in configuration if a value was not set
|
||||
if page.AppName == "" {
|
||||
page.AppName = c.Container.Config.App.Name
|
||||
}
|
||||
|
||||
// Check if this is an HTMX non-boosted request which indicates that only partial
|
||||
// content should be rendered
|
||||
if page.HTMX.Request.Enabled && !page.HTMX.Request.Boosted {
|
||||
// Parse and execute the templates only for the content portion of the page
|
||||
// The templates used for this partial request will be:
|
||||
// 1. The base htmx template which omits the layout and only includes the content template
|
||||
// 2. The content template specified in Page.Name
|
||||
// 3. All templates within the components directory
|
||||
// Also included is the function map provided by the funcmap package
|
||||
buf, err = c.Container.TemplateRenderer.
|
||||
Parse().
|
||||
Group("page:htmx").
|
||||
Key(page.Name).
|
||||
Base("htmx").
|
||||
Files(
|
||||
"htmx",
|
||||
fmt.Sprintf("pages/%s", page.Name),
|
||||
).
|
||||
Directories("components").
|
||||
Execute(page)
|
||||
} else {
|
||||
// Parse and execute the templates for the Page
|
||||
// As mentioned in the documentation for the Page struct, the templates used for the page will be:
|
||||
// 1. The layout/base template specified in Page.Layout
|
||||
// 2. The content template specified in Page.Name
|
||||
// 3. All templates within the components directory
|
||||
// Also included is the function map provided by the funcmap package
|
||||
buf, err = c.Container.TemplateRenderer.
|
||||
Parse().
|
||||
Group("page").
|
||||
Key(page.Name).
|
||||
Base(page.Layout).
|
||||
Files(
|
||||
fmt.Sprintf("layouts/%s", page.Layout),
|
||||
fmt.Sprintf("pages/%s", page.Name),
|
||||
).
|
||||
Directories("components").
|
||||
Execute(page)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return c.Fail(err, "failed to parse and execute templates")
|
||||
}
|
||||
|
||||
// Set the status code
|
||||
ctx.Response().Status = page.StatusCode
|
||||
|
||||
// Set any headers
|
||||
for k, v := range page.Headers {
|
||||
ctx.Response().Header().Set(k, v)
|
||||
}
|
||||
|
||||
// Apply the HTMX response, if one
|
||||
if page.HTMX.Response != nil {
|
||||
page.HTMX.Response.Apply(ctx)
|
||||
}
|
||||
|
||||
// Cache this page, if caching was enabled
|
||||
c.cachePage(ctx, page, buf)
|
||||
|
||||
return ctx.HTMLBlob(ctx.Response().Status, buf.Bytes())
|
||||
}
|
||||
|
||||
// cachePage caches the HTML for a given Page if the Page has caching enabled
|
||||
func (c *Controller) cachePage(ctx echo.Context, page Page, html *bytes.Buffer) {
|
||||
if !page.Cache.Enabled || page.IsAuth {
|
||||
return
|
||||
}
|
||||
|
||||
// If no expiration time was provided, default to the configuration value
|
||||
if page.Cache.Expiration == 0 {
|
||||
page.Cache.Expiration = c.Container.Config.Cache.Expiration.Page
|
||||
}
|
||||
|
||||
// Extract the headers
|
||||
headers := make(map[string]string)
|
||||
for k, v := range ctx.Response().Header() {
|
||||
headers[k] = v[0]
|
||||
}
|
||||
|
||||
// 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()
|
||||
cp := middleware.CachedPage{
|
||||
URL: key,
|
||||
HTML: html.Bytes(),
|
||||
Headers: headers,
|
||||
StatusCode: ctx.Response().Status,
|
||||
}
|
||||
|
||||
err := c.Container.Cache.
|
||||
Set().
|
||||
Group(middleware.CachedPageGroup).
|
||||
Key(key).
|
||||
Tags(page.Cache.Tags...).
|
||||
Expiration(page.Cache.Expiration).
|
||||
Data(cp).
|
||||
Save(ctx.Request().Context())
|
||||
|
||||
switch {
|
||||
case err == nil:
|
||||
ctx.Logger().Info("cached page")
|
||||
case !context.IsCanceledError(err):
|
||||
ctx.Logger().Errorf("failed to cache page: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Redirect redirects to a given route name with optional route parameters
|
||||
func (c *Controller) Redirect(ctx echo.Context, route string, routeParams ...interface{}) error {
|
||||
url := ctx.Echo().Reverse(route, routeParams...)
|
||||
|
||||
if htmx.GetRequest(ctx).Boosted {
|
||||
htmx.Response{
|
||||
Redirect: url,
|
||||
}.Apply(ctx)
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return ctx.Redirect(http.StatusFound, url)
|
||||
}
|
||||
}
|
||||
|
||||
// Fail is a helper to fail a request by returning a 500 error and logging the error
|
||||
func (c *Controller) Fail(err error, log string) error {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("%s: %v", log, err))
|
||||
}
|
||||
187
pkg/controller/controller_test.go
Normal file
187
pkg/controller/controller_test.go
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/mikestefanello/pagoda/config"
|
||||
"github.com/mikestefanello/pagoda/pkg/htmx"
|
||||
"github.com/mikestefanello/pagoda/pkg/middleware"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
"github.com/mikestefanello/pagoda/pkg/tests"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
var (
|
||||
c *services.Container
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
// Set the environment to test
|
||||
config.SwitchEnvironment(config.EnvTest)
|
||||
|
||||
// Create a new container
|
||||
c = services.NewContainer()
|
||||
|
||||
// Run tests
|
||||
exitVal := m.Run()
|
||||
|
||||
// Shutdown the container
|
||||
if err := c.Shutdown(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
os.Exit(exitVal)
|
||||
}
|
||||
|
||||
func TestController_Redirect(t *testing.T) {
|
||||
c.Web.GET("/path/:first/and/:second", func(c echo.Context) error {
|
||||
return nil
|
||||
}).Name = "redirect-test"
|
||||
|
||||
ctx, _ := tests.NewContext(c.Web, "/abc")
|
||||
ctr := NewController(c)
|
||||
err := ctr.Redirect(ctx, "redirect-test", "one", "two")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "/path/one/and/two", ctx.Response().Header().Get(echo.HeaderLocation))
|
||||
assert.Equal(t, http.StatusFound, ctx.Response().Status)
|
||||
}
|
||||
|
||||
func TestController_RenderPage(t *testing.T) {
|
||||
setup := func() (echo.Context, *httptest.ResponseRecorder, Controller, Page) {
|
||||
ctx, rec := tests.NewContext(c.Web, "/test/TestController_RenderPage")
|
||||
tests.InitSession(ctx)
|
||||
ctr := NewController(c)
|
||||
|
||||
p := NewPage(ctx)
|
||||
p.Name = "home"
|
||||
p.Layout = "main"
|
||||
p.Cache.Enabled = false
|
||||
p.Headers["A"] = "b"
|
||||
p.Headers["C"] = "d"
|
||||
p.StatusCode = http.StatusCreated
|
||||
return ctx, rec, ctr, p
|
||||
}
|
||||
|
||||
t.Run("missing name", func(t *testing.T) {
|
||||
// Rendering should fail if the Page has no name
|
||||
ctx, _, ctr, p := setup()
|
||||
p.Name = ""
|
||||
err := ctr.RenderPage(ctx, p)
|
||||
assert.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("no page cache", func(t *testing.T) {
|
||||
ctx, _, ctr, p := setup()
|
||||
err := ctr.RenderPage(ctx, p)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Check status code and headers
|
||||
assert.Equal(t, http.StatusCreated, ctx.Response().Status)
|
||||
for k, v := range p.Headers {
|
||||
assert.Equal(t, v, ctx.Response().Header().Get(k))
|
||||
}
|
||||
|
||||
// Check the template cache
|
||||
parsed, err := c.TemplateRenderer.Load("page", p.Name)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Check that all expected templates were parsed.
|
||||
// This includes the name, layout and all components
|
||||
expectedTemplates := make(map[string]bool)
|
||||
expectedTemplates[p.Name+config.TemplateExt] = true
|
||||
expectedTemplates[p.Layout+config.TemplateExt] = true
|
||||
components, err := ioutil.ReadDir(c.TemplateRenderer.GetTemplatesPath() + "/components")
|
||||
require.NoError(t, err)
|
||||
for _, f := range components {
|
||||
expectedTemplates[f.Name()] = true
|
||||
}
|
||||
|
||||
for _, v := range parsed.Template.Templates() {
|
||||
delete(expectedTemplates, v.Name())
|
||||
}
|
||||
assert.Empty(t, expectedTemplates)
|
||||
})
|
||||
|
||||
t.Run("htmx rendering", func(t *testing.T) {
|
||||
ctx, _, ctr, p := setup()
|
||||
p.HTMX.Request.Enabled = true
|
||||
p.HTMX.Response = &htmx.Response{
|
||||
Trigger: "trigger",
|
||||
}
|
||||
err := ctr.RenderPage(ctx, p)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Check HTMX header
|
||||
assert.Equal(t, "trigger", ctx.Response().Header().Get(htmx.HeaderTrigger))
|
||||
|
||||
// Check the template cache
|
||||
parsed, err := c.TemplateRenderer.Load("page:htmx", p.Name)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Check that all expected templates were parsed.
|
||||
// This includes the name, htmx and all components
|
||||
expectedTemplates := make(map[string]bool)
|
||||
expectedTemplates[p.Name+config.TemplateExt] = true
|
||||
expectedTemplates["htmx"+config.TemplateExt] = true
|
||||
components, err := ioutil.ReadDir(c.TemplateRenderer.GetTemplatesPath() + "/components")
|
||||
require.NoError(t, err)
|
||||
for _, f := range components {
|
||||
expectedTemplates[f.Name()] = true
|
||||
}
|
||||
|
||||
for _, v := range parsed.Template.Templates() {
|
||||
delete(expectedTemplates, v.Name())
|
||||
}
|
||||
assert.Empty(t, expectedTemplates)
|
||||
})
|
||||
|
||||
t.Run("page cache", func(t *testing.T) {
|
||||
ctx, rec, ctr, p := setup()
|
||||
p.Cache.Enabled = true
|
||||
p.Cache.Tags = []string{"tag1"}
|
||||
err := ctr.RenderPage(ctx, p)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Fetch from the cache
|
||||
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
|
||||
cp, ok := res.(*middleware.CachedPage)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, p.URL, cp.URL)
|
||||
assert.Equal(t, p.Headers, cp.Headers)
|
||||
assert.Equal(t, p.StatusCode, cp.StatusCode)
|
||||
assert.Equal(t, rec.Body.Bytes(), cp.HTML)
|
||||
|
||||
// Clear the tag
|
||||
err = c.Cache.
|
||||
Flush().
|
||||
Tags(p.Cache.Tags[0]).
|
||||
Execute(context.Background())
|
||||
require.NoError(t, err)
|
||||
|
||||
// Refetch from the cache and expect no results
|
||||
_, err = c.Cache.
|
||||
Get().
|
||||
Group(middleware.CachedPageGroup).
|
||||
Key(p.URL).
|
||||
Type(new(middleware.CachedPage)).
|
||||
Fetch(context.Background())
|
||||
assert.Error(t, err)
|
||||
})
|
||||
}
|
||||
104
pkg/controller/form.go
Normal file
104
pkg/controller/form.go
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
package controller
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
// FormSubmission represents the state of the submission of a form, not including the form itself
|
||||
type FormSubmission struct {
|
||||
// IsSubmitted indicates if the form has been submitted
|
||||
IsSubmitted bool
|
||||
|
||||
// Errors stores a slice of error message strings keyed by form struct field name
|
||||
Errors map[string][]string
|
||||
}
|
||||
|
||||
// Process processes a submission for a form
|
||||
func (f *FormSubmission) Process(ctx echo.Context, form interface{}) error {
|
||||
f.Errors = make(map[string][]string)
|
||||
f.IsSubmitted = true
|
||||
|
||||
// Validate the form
|
||||
if err := ctx.Validate(form); err != nil {
|
||||
f.setErrorMessages(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// HasErrors indicates if the submission has any validation errors
|
||||
func (f FormSubmission) HasErrors() bool {
|
||||
if f.Errors == nil {
|
||||
return false
|
||||
}
|
||||
return len(f.Errors) > 0
|
||||
}
|
||||
|
||||
// FieldHasErrors indicates if a given field on the form has any validation errors
|
||||
func (f FormSubmission) FieldHasErrors(fieldName string) bool {
|
||||
return len(f.GetFieldErrors(fieldName)) > 0
|
||||
}
|
||||
|
||||
// SetFieldError sets an error message for a given field name
|
||||
func (f *FormSubmission) SetFieldError(fieldName string, message string) {
|
||||
if f.Errors == nil {
|
||||
f.Errors = make(map[string][]string)
|
||||
}
|
||||
f.Errors[fieldName] = append(f.Errors[fieldName], message)
|
||||
}
|
||||
|
||||
// GetFieldErrors gets the errors for a given field name
|
||||
func (f FormSubmission) GetFieldErrors(fieldName string) []string {
|
||||
if f.Errors == nil {
|
||||
return []string{}
|
||||
}
|
||||
return f.Errors[fieldName]
|
||||
}
|
||||
|
||||
// GetFieldStatusClass returns an HTML class based on the status of the field
|
||||
func (f FormSubmission) GetFieldStatusClass(fieldName string) string {
|
||||
if f.IsSubmitted {
|
||||
if f.FieldHasErrors(fieldName) {
|
||||
return "is-danger"
|
||||
}
|
||||
return "is-success"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// IsDone indicates if the submission is considered done which is when it has been submitted
|
||||
// and there are no errors.
|
||||
func (f FormSubmission) IsDone() bool {
|
||||
return f.IsSubmitted && !f.HasErrors()
|
||||
}
|
||||
|
||||
// setErrorMessages sets errors messages on the submission for all fields that failed validation
|
||||
func (f *FormSubmission) setErrorMessages(err error) {
|
||||
// Only this is supported right now
|
||||
ves, ok := err.(validator.ValidationErrors)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
for _, ve := range ves {
|
||||
var message string
|
||||
|
||||
// Provide better error messages depending on the failed validation tag
|
||||
// This should be expanded as you use additional tags in your validation
|
||||
switch ve.Tag() {
|
||||
case "required":
|
||||
message = "This field is required."
|
||||
case "email":
|
||||
message = "Enter a valid email address."
|
||||
case "eqfield":
|
||||
message = "Does not match."
|
||||
default:
|
||||
message = "Invalid value."
|
||||
}
|
||||
|
||||
// Add the error
|
||||
f.SetFieldError(ve.Field(), message)
|
||||
}
|
||||
}
|
||||
36
pkg/controller/form_test.go
Normal file
36
pkg/controller/form_test.go
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
package controller
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/mikestefanello/pagoda/pkg/tests"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestFormSubmission(t *testing.T) {
|
||||
type formTest struct {
|
||||
Name string `validate:"required"`
|
||||
Email string `validate:"required,email"`
|
||||
Submission FormSubmission
|
||||
}
|
||||
|
||||
ctx, _ := tests.NewContext(c.Web, "/")
|
||||
form := formTest{
|
||||
Name: "",
|
||||
Email: "a@a.com",
|
||||
}
|
||||
err := form.Submission.Process(ctx, form)
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.True(t, form.Submission.HasErrors())
|
||||
assert.True(t, form.Submission.FieldHasErrors("Name"))
|
||||
assert.False(t, form.Submission.FieldHasErrors("Email"))
|
||||
require.Len(t, form.Submission.GetFieldErrors("Name"), 1)
|
||||
assert.Len(t, form.Submission.GetFieldErrors("Email"), 0)
|
||||
assert.Equal(t, "This field is required.", form.Submission.GetFieldErrors("Name")[0])
|
||||
assert.Equal(t, "is-danger", form.Submission.GetFieldStatusClass("Name"))
|
||||
assert.Equal(t, "is-success", form.Submission.GetFieldStatusClass("Email"))
|
||||
assert.False(t, form.Submission.IsDone())
|
||||
}
|
||||
161
pkg/controller/page.go
Normal file
161
pkg/controller/page.go
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
package controller
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/mikestefanello/pagoda/ent"
|
||||
"github.com/mikestefanello/pagoda/pkg/context"
|
||||
"github.com/mikestefanello/pagoda/pkg/htmx"
|
||||
"github.com/mikestefanello/pagoda/pkg/msg"
|
||||
|
||||
echomw "github.com/labstack/echo/v4/middleware"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
// Page consists of all data that will be used to render a page response for a given controller.
|
||||
// While it's not required for a controller to render a Page on a route, this is the common data
|
||||
// object that will be passed to the templates, making it easy for all controllers to share
|
||||
// functionality both on the back and frontend. The Page can be expanded to include anything else
|
||||
// your app wants to support.
|
||||
// Methods on this page also then become available in the templates, which can be more useful than
|
||||
// the funcmap if your methods require data stored in the page, such as the context.
|
||||
type Page struct {
|
||||
// AppName stores the name of the application.
|
||||
// If omitted, the configuration value will be used.
|
||||
AppName string
|
||||
|
||||
// Title stores the title of the page
|
||||
Title string
|
||||
|
||||
// Context stores the request context
|
||||
Context echo.Context
|
||||
|
||||
// ToURL is a function to convert a route name and optional route parameters to a URL
|
||||
ToURL func(name string, params ...interface{}) string
|
||||
|
||||
// Path stores the path of the current request
|
||||
Path string
|
||||
|
||||
// URL stores the URL of the current request
|
||||
URL string
|
||||
|
||||
// Data stores whatever additional data that needs to be passed to the templates.
|
||||
// This is what the controller uses to pass the content of the page.
|
||||
Data interface{}
|
||||
|
||||
// Form stores a struct that represents a form on the page.
|
||||
// This should be a struct with fields for each form field, using both "form" and "validate" tags
|
||||
// It should also contain a Submission field of type FormSubmission if you wish to have validation
|
||||
// messagesa and markup presented to the user
|
||||
Form interface{}
|
||||
|
||||
// Layout stores the name of the layout base template file which will be used when the page is rendered.
|
||||
// This should match a template file located within the layouts directory inside the templates directory.
|
||||
// The template extension should not be included in this value.
|
||||
Layout string
|
||||
|
||||
// Name stores the name of the page as well as the name of the template file which will be used to render
|
||||
// the content portion of the layout template.
|
||||
// This should match a template file located within the pages directory inside the templates directory.
|
||||
// The template extension should not be included in this value.
|
||||
Name string
|
||||
|
||||
// IsHome stores whether the requested page is the home page or not
|
||||
IsHome bool
|
||||
|
||||
// IsAuth stores whether or not the user is authenticated
|
||||
IsAuth bool
|
||||
|
||||
// AuthUser stores the authenticated user
|
||||
AuthUser *ent.User
|
||||
|
||||
// StatusCode stores the HTTP status code that will be returned
|
||||
StatusCode int
|
||||
|
||||
// Metatags stores metatag values
|
||||
Metatags struct {
|
||||
// Description stores the description metatag value
|
||||
Description string
|
||||
|
||||
// Keywords stores the keywords metatag values
|
||||
Keywords []string
|
||||
}
|
||||
|
||||
// Pager stores a pager which can be used to page lists of results
|
||||
Pager Pager
|
||||
|
||||
// CSRF stores the CSRF token for the given request.
|
||||
// This will only be populated if the CSRF middleware is in effect for the given request.
|
||||
// If this is populated, all forms must include this value otherwise the requests will be rejected.
|
||||
CSRF string
|
||||
|
||||
// Headers stores a list of HTTP headers and values to be set on the response
|
||||
Headers map[string]string
|
||||
|
||||
// RequestID stores the ID of the given request.
|
||||
// This will only be populated if the request ID middleware is in effect for the given request.
|
||||
RequestID string
|
||||
|
||||
HTMX struct {
|
||||
Request htmx.Request
|
||||
Response *htmx.Response
|
||||
}
|
||||
|
||||
// Cache stores values for caching the response of this page
|
||||
Cache struct {
|
||||
// Enabled dictates if the response of this page should be cached.
|
||||
// Cached responses are served via middleware.
|
||||
Enabled bool
|
||||
|
||||
// Expiration stores the amount of time that the cache entry should live for before expiring.
|
||||
// If omitted, the configuration value will be used.
|
||||
Expiration time.Duration
|
||||
|
||||
// Tags stores a list of tags to apply to the cache entry.
|
||||
// These are useful when invalidating cache for dynamic events such as entity operations.
|
||||
Tags []string
|
||||
}
|
||||
}
|
||||
|
||||
// NewPage creates and initiatizes a new Page for a given request context
|
||||
func NewPage(ctx echo.Context) Page {
|
||||
p := Page{
|
||||
Context: ctx,
|
||||
ToURL: ctx.Echo().Reverse,
|
||||
Path: ctx.Request().URL.Path,
|
||||
URL: ctx.Request().URL.String(),
|
||||
StatusCode: http.StatusOK,
|
||||
Pager: NewPager(ctx, DefaultItemsPerPage),
|
||||
Headers: make(map[string]string),
|
||||
RequestID: ctx.Response().Header().Get(echo.HeaderXRequestID),
|
||||
}
|
||||
|
||||
p.IsHome = p.Path == "/"
|
||||
|
||||
if csrf := ctx.Get(echomw.DefaultCSRFConfig.ContextKey); csrf != nil {
|
||||
p.CSRF = csrf.(string)
|
||||
}
|
||||
|
||||
if u := ctx.Get(context.AuthenticatedUserKey); u != nil {
|
||||
p.IsAuth = true
|
||||
p.AuthUser = u.(*ent.User)
|
||||
}
|
||||
|
||||
p.HTMX.Request = htmx.GetRequest(ctx)
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
// GetMessages gets all flash messages for a given type.
|
||||
// This allows for easy access to flash messages from the templates.
|
||||
func (p Page) GetMessages(typ msg.Type) []template.HTML {
|
||||
strs := msg.Get(p.Context, typ)
|
||||
ret := make([]template.HTML, len(strs))
|
||||
for k, v := range strs {
|
||||
ret[k] = template.HTML(v)
|
||||
}
|
||||
return ret
|
||||
}
|
||||
75
pkg/controller/page_test.go
Normal file
75
pkg/controller/page_test.go
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
package controller
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/mikestefanello/pagoda/pkg/context"
|
||||
"github.com/mikestefanello/pagoda/pkg/msg"
|
||||
"github.com/mikestefanello/pagoda/pkg/tests"
|
||||
|
||||
echomw "github.com/labstack/echo/v4/middleware"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNewPage(t *testing.T) {
|
||||
ctx, _ := tests.NewContext(c.Web, "/")
|
||||
p := NewPage(ctx)
|
||||
assert.Same(t, ctx, p.Context)
|
||||
assert.NotNil(t, p.ToURL)
|
||||
assert.Equal(t, "/", p.Path)
|
||||
assert.Equal(t, "/", p.URL)
|
||||
assert.Equal(t, http.StatusOK, p.StatusCode)
|
||||
assert.Equal(t, NewPager(ctx, DefaultItemsPerPage), p.Pager)
|
||||
assert.Empty(t, p.Headers)
|
||||
assert.True(t, p.IsHome)
|
||||
assert.False(t, p.IsAuth)
|
||||
assert.Empty(t, p.CSRF)
|
||||
assert.Empty(t, p.RequestID)
|
||||
assert.False(t, p.Cache.Enabled)
|
||||
|
||||
ctx, _ = tests.NewContext(c.Web, "/abc?def=123")
|
||||
usr, err := tests.CreateUser(c.ORM)
|
||||
require.NoError(t, err)
|
||||
ctx.Set(context.AuthenticatedUserKey, usr)
|
||||
ctx.Set(echomw.DefaultCSRFConfig.ContextKey, "csrf")
|
||||
p = NewPage(ctx)
|
||||
assert.Equal(t, "/abc", p.Path)
|
||||
assert.Equal(t, "/abc?def=123", p.URL)
|
||||
assert.False(t, p.IsHome)
|
||||
assert.True(t, p.IsAuth)
|
||||
assert.Equal(t, usr, p.AuthUser)
|
||||
assert.Equal(t, "csrf", p.CSRF)
|
||||
}
|
||||
|
||||
func TestPage_GetMessages(t *testing.T) {
|
||||
ctx, _ := tests.NewContext(c.Web, "/")
|
||||
tests.InitSession(ctx)
|
||||
p := NewPage(ctx)
|
||||
|
||||
// Set messages
|
||||
msgTests := make(map[msg.Type][]string)
|
||||
msgTests[msg.TypeWarning] = []string{
|
||||
"abc",
|
||||
"def",
|
||||
}
|
||||
msgTests[msg.TypeInfo] = []string{
|
||||
"123",
|
||||
"456",
|
||||
}
|
||||
for typ, values := range msgTests {
|
||||
for _, value := range values {
|
||||
msg.Set(ctx, typ, value)
|
||||
}
|
||||
}
|
||||
|
||||
// Get the messages
|
||||
for typ, values := range msgTests {
|
||||
msgs := p.GetMessages(typ)
|
||||
|
||||
for i, message := range msgs {
|
||||
assert.Equal(t, values[i], string(message))
|
||||
}
|
||||
}
|
||||
}
|
||||
80
pkg/controller/pager.go
Normal file
80
pkg/controller/pager.go
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
package controller
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultItemsPerPage stores the default amount of items per page
|
||||
DefaultItemsPerPage = 20
|
||||
|
||||
// PageQueryKey stores the query key used to indicate the current page
|
||||
PageQueryKey = "page"
|
||||
)
|
||||
|
||||
// Pager provides a mechanism to allow a user to page results via a query parameter
|
||||
type Pager struct {
|
||||
// Items stores the total amount of items in the result set
|
||||
Items int
|
||||
|
||||
// Page stores the current page number
|
||||
Page int
|
||||
|
||||
// ItemsPerPage stores the amount of items to display per page
|
||||
ItemsPerPage int
|
||||
|
||||
// Pages stores the total amount of pages in the result set
|
||||
Pages int
|
||||
}
|
||||
|
||||
// NewPager creates a new Pager
|
||||
func NewPager(ctx echo.Context, itemsPerPage int) Pager {
|
||||
p := Pager{
|
||||
ItemsPerPage: itemsPerPage,
|
||||
Page: 1,
|
||||
}
|
||||
|
||||
if page := ctx.QueryParam(PageQueryKey); page != "" {
|
||||
if pageInt, err := strconv.Atoi(page); err == nil {
|
||||
if pageInt > 0 {
|
||||
p.Page = pageInt
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
// SetItems sets the amount of items in total for the pager and calculate the amount
|
||||
// of total pages based off on the item per page.
|
||||
// This should be used rather than setting either items or pages directly.
|
||||
func (p *Pager) SetItems(items int) {
|
||||
p.Items = items
|
||||
p.Pages = int(math.Ceil(float64(items) / float64(p.ItemsPerPage)))
|
||||
|
||||
if p.Page > p.Pages {
|
||||
p.Page = p.Pages
|
||||
}
|
||||
}
|
||||
|
||||
// IsBeginning determines if the pager is at the beginning of the pages
|
||||
func (p Pager) IsBeginning() bool {
|
||||
return p.Page == 1
|
||||
}
|
||||
|
||||
// IsEnd determines if the pager is at the end of the pages
|
||||
func (p Pager) IsEnd() bool {
|
||||
return p.Page >= p.Pages
|
||||
}
|
||||
|
||||
// GetOffset determines the offset of the results in order to get the items for
|
||||
// the current page
|
||||
func (p Pager) GetOffset() int {
|
||||
if p.Page == 0 {
|
||||
p.Page = 1
|
||||
}
|
||||
return (p.Page - 1) * p.ItemsPerPage
|
||||
}
|
||||
67
pkg/controller/pager_test.go
Normal file
67
pkg/controller/pager_test.go
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
package controller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/mikestefanello/pagoda/pkg/tests"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestNewPager(t *testing.T) {
|
||||
ctx, _ := tests.NewContext(c.Web, "/")
|
||||
pgr := NewPager(ctx, 10)
|
||||
assert.Equal(t, 10, pgr.ItemsPerPage)
|
||||
assert.Equal(t, 1, pgr.Page)
|
||||
assert.Equal(t, 0, pgr.Items)
|
||||
assert.Equal(t, 0, pgr.Pages)
|
||||
|
||||
ctx, _ = tests.NewContext(c.Web, fmt.Sprintf("/abc?%s=%d", PageQueryKey, 2))
|
||||
pgr = NewPager(ctx, 10)
|
||||
assert.Equal(t, 2, pgr.Page)
|
||||
|
||||
ctx, _ = tests.NewContext(c.Web, fmt.Sprintf("/abc?%s=%d", PageQueryKey, -2))
|
||||
pgr = NewPager(ctx, 10)
|
||||
assert.Equal(t, 1, pgr.Page)
|
||||
}
|
||||
|
||||
func TestPager_SetItems(t *testing.T) {
|
||||
ctx, _ := tests.NewContext(c.Web, "/")
|
||||
pgr := NewPager(ctx, 20)
|
||||
pgr.SetItems(100)
|
||||
assert.Equal(t, 100, pgr.Items)
|
||||
assert.Equal(t, 5, pgr.Pages)
|
||||
}
|
||||
|
||||
func TestPager_IsBeginning(t *testing.T) {
|
||||
ctx, _ := tests.NewContext(c.Web, "/")
|
||||
pgr := NewPager(ctx, 20)
|
||||
pgr.Pages = 10
|
||||
assert.True(t, pgr.IsBeginning())
|
||||
pgr.Page = 2
|
||||
assert.False(t, pgr.IsBeginning())
|
||||
pgr.Page = 1
|
||||
assert.True(t, pgr.IsBeginning())
|
||||
}
|
||||
|
||||
func TestPager_IsEnd(t *testing.T) {
|
||||
ctx, _ := tests.NewContext(c.Web, "/")
|
||||
pgr := NewPager(ctx, 20)
|
||||
pgr.Pages = 10
|
||||
assert.False(t, pgr.IsEnd())
|
||||
pgr.Page = 10
|
||||
assert.True(t, pgr.IsEnd())
|
||||
pgr.Page = 1
|
||||
assert.False(t, pgr.IsEnd())
|
||||
}
|
||||
|
||||
func TestPager_GetOffset(t *testing.T) {
|
||||
ctx, _ := tests.NewContext(c.Web, "/")
|
||||
pgr := NewPager(ctx, 20)
|
||||
assert.Equal(t, 0, pgr.GetOffset())
|
||||
pgr.Page = 2
|
||||
assert.Equal(t, 20, pgr.GetOffset())
|
||||
pgr.Page = 3
|
||||
assert.Equal(t, 40, pgr.GetOffset())
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue