package data import ( "strings" "git.runcible.io/learning/pulley/internal/validator" ) type Filters struct { Page int PageSize int Sort string SortSafelist []string } func ValidateFilters(v *validator.Validator, f Filters) { v.Check(f.Page > 0, "page", "must be greater than zero") v.Check(f.Page < 10_000_000, "page", "must be a maximum of 10 million") v.Check(f.PageSize > 0, "page_size", "must be greater than zero") v.Check(f.PageSize <= 100, "page_size", "must be a maximum of 100") v.Check(validator.PermittedValue(f.Sort, f.SortSafelist...), "sort", "invalid sort value") } // sortColumn checks that the client-provided Sort field matches one of the entries in our safelist // and if it does, extract the column name from the Sort field. func (f Filters) sortColumn() string { for _, safeValue := range f.SortSafelist { if f.Sort == safeValue { return strings.TrimPrefix(f.Sort, "-") } } // ValidateFilters should have checked this, but we are extra careful of sql injection. panic("unsafe sort parameter: " + f.Sort) } // sortDirection returns the sort direction depending on the prefix // character of the Sort field. func (f Filters) sortDirection() string { if strings.HasPrefix(f.Sort, "-") { return "DESC" } return "ASC" }