Skip to content

Fix: Query param deepObject return without assign on !required #68

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bindparam.go
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,7 @@ func BindQueryParameter(style string, explode bool, required bool, paramName str
if !explode {
return errors.New("deepObjects must be exploded")
}
return UnmarshalDeepObject(dest, paramName, queryParams)
return unmarshalDeepObject(dest, paramName, queryParams, required)
case "spaceDelimited", "pipeDelimited":
return fmt.Errorf("query arguments of style '%s' aren't yet supported", style)
default:
Expand Down
4 changes: 4 additions & 0 deletions bindparam_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,10 @@ func TestBindQueryParameter(t *testing.T) {
err := BindQueryParameter("deepObject", true, false, paramName, queryParams, &actual)
assert.NoError(t, err)
assert.Equal(t, expectedDeepObject, actual)

// If we require values, we require errors when they're not present.
err = BindQueryParameter("deepObject", true, true, "notfound", queryParams, &actual)
assert.Error(t, err)
})

t.Run("form", func(t *testing.T) {
Expand Down
12 changes: 12 additions & 0 deletions deepobject.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ func makeFieldOrValue(paths [][]string, values []string) fieldOrValue {
}

func UnmarshalDeepObject(dst interface{}, paramName string, params url.Values) error {
return unmarshalDeepObject(dst, paramName, params, false)
}

func unmarshalDeepObject(dst interface{}, paramName string, params url.Values, required bool) error {
// Params are all the query args, so we need those that look like
// "paramName["...
var fieldNames []string
Expand All @@ -141,6 +145,14 @@ func UnmarshalDeepObject(dst interface{}, paramName string, params url.Values) e
}
}

if len(fieldNames) == 0 {
if required {
return fmt.Errorf("query parameter '%s' is required", paramName)
} else {
return nil
}
}

// Now, for each field, reconstruct its subscript path and value
paths := make([][]string, len(fieldNames))
for i, path := range fieldNames {
Expand Down