refactored for maintainability
This commit is contained in:
70
internal/validation/querys.go
Normal file
70
internal/validation/querys.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package validation
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.haelnorr.com/h/golib/hws"
|
||||
"git.haelnorr.com/h/timefmt"
|
||||
)
|
||||
|
||||
// QueryGetter wraps http.Request to get query values
|
||||
type QueryGetter struct {
|
||||
r *http.Request
|
||||
checks []*ValidationRule
|
||||
}
|
||||
|
||||
func NewQueryGetter(r *http.Request) *QueryGetter {
|
||||
return &QueryGetter{r: r, checks: []*ValidationRule{}}
|
||||
}
|
||||
|
||||
func (q *QueryGetter) Get(key string) string {
|
||||
return q.r.URL.Query().Get(key)
|
||||
}
|
||||
|
||||
func (q *QueryGetter) getChecks() []*ValidationRule {
|
||||
return q.checks
|
||||
}
|
||||
|
||||
func (q *QueryGetter) AddCheck(check *ValidationRule) {
|
||||
q.checks = append(q.checks, check)
|
||||
}
|
||||
|
||||
func (q *QueryGetter) ValidateChecks() []*ValidationRule {
|
||||
return validate(q)
|
||||
}
|
||||
|
||||
func (q *QueryGetter) String(key string) *StringField {
|
||||
return newStringField(key, q)
|
||||
}
|
||||
|
||||
func (q *QueryGetter) Int(key string) *IntField {
|
||||
return newIntField(key, q)
|
||||
}
|
||||
|
||||
func (q *QueryGetter) Time(key string, format *timefmt.Format) *TimeField {
|
||||
return newTimeField(key, format, q)
|
||||
}
|
||||
|
||||
func (q *QueryGetter) Validate() bool {
|
||||
return len(validate(q)) == 0
|
||||
}
|
||||
|
||||
// ValidateAndNotify runs the provided validation checks and sends a notification for each failed check
|
||||
// Returns true if all checks passed
|
||||
func (q *QueryGetter) ValidateAndNotify(
|
||||
s *hws.Server,
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
) bool {
|
||||
return validateAndNotify(s, w, r, q)
|
||||
}
|
||||
|
||||
// ValidateAndError runs the provided validation checks and renders an error page with all the error messages
|
||||
// Returns true if all checks passed
|
||||
func (q *QueryGetter) ValidateAndError(
|
||||
s *hws.Server,
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
) bool {
|
||||
return validateAndError(s, w, r, q)
|
||||
}
|
||||
Reference in New Issue
Block a user