refactored for maintainability
This commit is contained in:
45
internal/handlers/pageopt_helpers.go
Normal file
45
internal/handlers/pageopt_helpers.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.haelnorr.com/h/golib/hws"
|
||||
"git.haelnorr.com/h/oslstats/internal/db"
|
||||
"git.haelnorr.com/h/oslstats/internal/validation"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
// pageOptsFromForm calls r.ParseForm and gets the pageOpts from the formdata.
|
||||
// It renders a Bad Request error page on fail
|
||||
// PageOpts will be nil on fail
|
||||
func pageOptsFromForm(s *hws.Server, w http.ResponseWriter, r *http.Request) *db.PageOpts {
|
||||
getter, ok := validation.ParseFormOrError(s, w, r)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return getPageOpts(s, w, r, getter)
|
||||
}
|
||||
|
||||
// pageOptsFromQuery gets the pageOpts from the request query and renders a Bad Request error page on fail
|
||||
// PageOpts will be nil on fail
|
||||
func pageOptsFromQuery(s *hws.Server, w http.ResponseWriter, r *http.Request) *db.PageOpts {
|
||||
return getPageOpts(s, w, r, validation.NewQueryGetter(r))
|
||||
}
|
||||
|
||||
func getPageOpts(s *hws.Server, w http.ResponseWriter, r *http.Request, g validation.Getter) *db.PageOpts {
|
||||
page := g.Int("page").Min(1).Value
|
||||
perPage := g.Int("per_page").Min(1).Max(100).Value
|
||||
order := g.String("order").TrimSpace().ToUpper().AllowedValues([]string{"ASC", "DESC"}).Value
|
||||
orderBy := g.String("order_by").TrimSpace().ToLower().Value
|
||||
valid := g.ValidateAndError(s, w, r)
|
||||
if !valid {
|
||||
return nil
|
||||
}
|
||||
pageOpts := &db.PageOpts{
|
||||
Page: page,
|
||||
PerPage: perPage,
|
||||
Order: bun.Order(order),
|
||||
OrderBy: orderBy,
|
||||
}
|
||||
return pageOpts
|
||||
}
|
||||
Reference in New Issue
Block a user