Skip to content

Commit

Permalink
sort allowed fields before returning in the error (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
cjmarkham authored Nov 23, 2023
1 parent b6a3d3d commit 19c1d12
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
4 changes: 2 additions & 2 deletions external/epsearchast/v3/validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,10 @@ func TestValidationReturnsErrorForBinaryOperatorsWhenAstUsesUnknownField(t *test
otherBinOp := binOps[(idx+1)%len(binOps)]

// Execute SUT
err = ValidateAstFieldAndOperators(ast, map[string][]string{"other_field": {otherBinOp}})
err = ValidateAstFieldAndOperators(ast, map[string][]string{"other_field": {otherBinOp}, "another_field": {otherBinOp}})

// Verification
require.ErrorContains(t, err, fmt.Sprintf("unknown field [amount] specified in search filter, allowed fields are [other_field]"))
require.EqualError(t, err, fmt.Sprintf("unknown field [amount] specified in search filter, allowed fields are [another_field other_field]"))
})
}

Expand Down
10 changes: 9 additions & 1 deletion external/epsearchast/v3/validating_visitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"github.com/go-playground/validator/v10"
"reflect"
"sort"
"strings"
)

Expand Down Expand Up @@ -154,7 +155,14 @@ func (v *validatingVisitor) isOperatorValidForField(operator, requestField strin
}

if _, ok := v.AllowedOperators[canonicalField]; !ok {
return false, fmt.Errorf("unknown field [%s] specified in search filter, allowed fields are %v", requestField, reflect.ValueOf(v.AllowedOperators).MapKeys())
allowedFields := reflect.ValueOf(v.AllowedOperators).MapKeys()
// Sort the allowed fields to give consistent errors
sortedAllowedFields := make([]string, len(allowedFields))
for i := range allowedFields {
sortedAllowedFields[i] = allowedFields[i].String()
}
sort.Strings(sortedAllowedFields)
return false, fmt.Errorf("unknown field [%s] specified in search filter, allowed fields are %v", requestField, sortedAllowedFields)
}

for _, op := range v.AllowedOperators[canonicalField] {
Expand Down

0 comments on commit 19c1d12

Please sign in to comment.