Skip to content

Commit 74d96b7

Browse files
authored
Improve error message for undefined arrays of objects (#1923)
1 parent c076063 commit 74d96b7

File tree

4 files changed

+31
-1
lines changed

4 files changed

+31
-1
lines changed

internal/fields/testdata/fields/fields.yml

+2
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,5 @@
8686
type: keyword
8787
normalize:
8888
- array
89+
- name: user.group.id
90+
type: keyword
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"user": {
3+
"group": [
4+
{
5+
"id": "42"
6+
},
7+
{
8+
"id": "0"
9+
}
10+
]
11+
}
12+
}

internal/fields/validate.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -584,7 +584,12 @@ func (v *Validator) validateScalarElement(key string, val interface{}, doc commo
584584
}
585585

586586
if definition == nil {
587-
return fmt.Errorf(`field "%s" is undefined`, key)
587+
switch val.(type) {
588+
case []any, []map[string]interface{}:
589+
return fmt.Errorf(`field "%s" is used as array of objects, expected explicit definition with type group or nested`, key)
590+
default:
591+
return fmt.Errorf(`field "%s" is undefined`, key)
592+
}
588593
}
589594

590595
// Convert numeric keyword fields to string for validation.

internal/fields/validate_test.go

+11
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,17 @@ func TestValidate_ipAddress(t *testing.T) {
148148
require.Empty(t, errs)
149149
}
150150

151+
func TestValidate_undefinedArrayOfObjects(t *testing.T) {
152+
validator, err := CreateValidatorForDirectory("testdata", WithSpecVersion("2.0.0"), WithDisabledDependencyManagement())
153+
require.NoError(t, err)
154+
require.NotNil(t, validator)
155+
156+
e := readSampleEvent(t, "testdata/undefined-array-of-objects.json")
157+
errs := validator.ValidateDocumentBody(e)
158+
require.Len(t, errs, 1)
159+
require.Contains(t, errs[0].Error(), `field "user.group" is used as array of objects, expected explicit definition with type group or nested`)
160+
}
161+
151162
func TestValidate_WithSpecVersion(t *testing.T) {
152163
validator, err := CreateValidatorForDirectory("testdata", WithSpecVersion("2.0.0"), WithDisabledDependencyManagement())
153164
require.NoError(t, err)

0 commit comments

Comments
 (0)