handle Optional Null Iterator selector

This commit is contained in:
Fabio Bozzo
2024-09-13 15:33:11 +02:00
parent a183b627be
commit 7060d4bb33
2 changed files with 14 additions and 3 deletions

View File

@@ -93,9 +93,20 @@ func resolve(sel Selector, subject ipld.Node, at []string) (ipld.Node, []ipld.No
// 2nd level: handle different node kinds (list, map, string, bytes) // 2nd level: handle different node kinds (list, map, string, bytes)
switch { switch {
case seg.Iterator(): case seg.Iterator():
if cur == nil { if cur == nil || cur.Kind() == datamodel.Kind_Null {
if seg.Optional() { if seg.Optional() {
cur = nil // build empty list
nb := basicnode.Prototype.List.NewBuilder()
assembler, err := nb.BeginList(0)
if err != nil {
return nil, nil, err
}
if err = assembler.Finish(); err != nil {
return nil, nil, err
}
return nb.Build(), nil, nil
} else { } else {
return nil, nil, newResolutionError(fmt.Sprintf("can not iterate over kind: %s", kindString(cur)), at) return nil, nil, newResolutionError(fmt.Sprintf("can not iterate over kind: %s", kindString(cur)), at)
} }

View File

@@ -30,7 +30,7 @@ func TestSupportedForms(t *testing.T) {
for _, testcase := range []Testcase{ for _, testcase := range []Testcase{
{Name: "Identity", Selector: `.`, Input: `{"x":1}`, Output: `{"x":1}`}, {Name: "Identity", Selector: `.`, Input: `{"x":1}`, Output: `{"x":1}`},
{Name: "Iterator", Selector: `.[]`, Input: `[1, 2]`, Output: `[1, 2]`}, {Name: "Iterator", Selector: `.[]`, Input: `[1, 2]`, Output: `[1, 2]`},
{Name: "Optional Null Iterator", Selector: `.[]?`, Input: `null`, Output: `()`}, {Name: "Optional Null Iterator", Selector: `.[]?`, Input: `null`, Output: `[]`},
{Name: "Optional Iterator", Selector: `.[][]?`, Input: `[[1], 2, [3]]`, Output: `[1, 3]`}, {Name: "Optional Iterator", Selector: `.[][]?`, Input: `[[1], 2, [3]]`, Output: `[1, 3]`},
{Name: "Object Key", Selector: `.x`, Input: `{"x": 1 }`, Output: `1`}, {Name: "Object Key", Selector: `.x`, Input: `{"x": 1 }`, Output: `1`},
{Name: "Quoted Key", Selector: `.["x"]`, Input: `{"x": 1}`, Output: `1`}, {Name: "Quoted Key", Selector: `.["x"]`, Input: `{"x": 1}`, Output: `1`},