Easier form and form submission handling.
This commit is contained in:
parent
ad4818aa8b
commit
4540276472
7 changed files with 175 additions and 116 deletions
34
pkg/form/form.go
Normal file
34
pkg/form/form.go
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
package form
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/pkg/context"
|
||||
)
|
||||
|
||||
// Get gets a form from the context or initializes a new copy if one is not set
|
||||
func Get[T any](ctx echo.Context) *T {
|
||||
if v := ctx.Get(context.FormKey); v != nil {
|
||||
return v.(*T)
|
||||
}
|
||||
var v T
|
||||
return &v
|
||||
}
|
||||
|
||||
// Set sets a form in the context and binds the request values to it
|
||||
func Set(ctx echo.Context, form any) error {
|
||||
ctx.Set(context.FormKey, form)
|
||||
|
||||
if err := ctx.Bind(form); err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("unable to bind form: %v", err))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Clear removes the form set in the context
|
||||
func Clear(ctx echo.Context) {
|
||||
ctx.Set(context.FormKey, nil)
|
||||
}
|
||||
59
pkg/form/form_test.go
Normal file
59
pkg/form/form_test.go
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
package form
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/pkg/tests"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestContextFuncs(t *testing.T) {
|
||||
e := echo.New()
|
||||
|
||||
type example struct {
|
||||
Name string `form:"name"`
|
||||
}
|
||||
|
||||
t.Run("get empty context", func(t *testing.T) {
|
||||
// Empty context, still return a form
|
||||
ctx, _ := tests.NewContext(e, "/")
|
||||
form := Get[example](ctx)
|
||||
assert.NotNil(t, form)
|
||||
})
|
||||
|
||||
t.Run("set bad request", func(t *testing.T) {
|
||||
// Set with a bad request
|
||||
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("abc=abc"))
|
||||
ctx := e.NewContext(req, httptest.NewRecorder())
|
||||
var form example
|
||||
err := Set(ctx, &form)
|
||||
assert.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("set", func(t *testing.T) {
|
||||
// Set and parse the values
|
||||
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("name=abc"))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
ctx := e.NewContext(req, httptest.NewRecorder())
|
||||
var form example
|
||||
err := Set(ctx, &form)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "abc", form.Name)
|
||||
|
||||
// Get again and expect the values were stored
|
||||
got := Get[example](ctx)
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, "abc", form.Name)
|
||||
|
||||
// Clear
|
||||
Clear(ctx)
|
||||
got = Get[example](ctx)
|
||||
require.NotNil(t, got)
|
||||
assert.Empty(t, got.Name)
|
||||
})
|
||||
}
|
||||
104
pkg/form/submission.go
Normal file
104
pkg/form/submission.go
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
package form
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
// Submission represents the state of the submission of a form, not including the form itself
|
||||
type Submission 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 *Submission) Process(ctx echo.Context, form any) 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 Submission) 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 Submission) FieldHasErrors(fieldName string) bool {
|
||||
return len(f.GetFieldErrors(fieldName)) > 0
|
||||
}
|
||||
|
||||
// SetFieldError sets an error message for a given field name
|
||||
func (f *Submission) 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 Submission) 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 Submission) 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 Submission) IsDone() bool {
|
||||
return f.IsSubmitted && !f.HasErrors()
|
||||
}
|
||||
|
||||
// setErrorMessages sets errors messages on the submission for all fields that failed validation
|
||||
func (f *Submission) 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)
|
||||
}
|
||||
}
|
||||
40
pkg/form/submission_test.go
Normal file
40
pkg/form/submission_test.go
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
package form
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
"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 Submission
|
||||
}
|
||||
|
||||
e := echo.New()
|
||||
e.Validator = services.NewValidator()
|
||||
ctx, _ := tests.NewContext(e, "/")
|
||||
form := formTest{
|
||||
Name: "",
|
||||
Email: "a@a.com",
|
||||
}
|
||||
err := form.Submission.Process(ctx, form)
|
||||
require.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())
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue