diff --git a/nodeutil/reflect.go b/nodeutil/reflect.go index a41d93e..f25c869 100644 --- a/nodeutil/reflect.go +++ b/nodeutil/reflect.go @@ -260,7 +260,9 @@ func (self Reflect) listSlice(v reflect.Value, onChange OnListValueChange) node. onChange(v) } entries = nil - return self.child(item), key, nil + // append() copies item to array, so we need to find new item in array and make further operations on it + appendedItem := v.Index(v.Len() - 1) + return self.child(appendedItem), key, nil } else if key != nil { if entries == nil { var err error @@ -454,6 +456,8 @@ func (self Reflect) create(t reflect.Type, m meta.Meta) reflect.Value { return reflect.MakeMap(t) case reflect.Slice: return reflect.MakeSlice(t, 0, 0) + case reflect.Struct: + return reflect.New(t).Elem() } panic(fmt.Sprintf("creating type not supported %v", t)) } diff --git a/nodeutil/reflect_test.go b/nodeutil/reflect_test.go index 1469ac8..e42b4ed 100644 --- a/nodeutil/reflect_test.go +++ b/nodeutil/reflect_test.go @@ -231,7 +231,7 @@ func TestReflect2Write(t *testing.T) { fc.RequireEqual(t, nil, sel.Delete()) fc.AssertEqual(t, 0, len(app.Birds)) } - // slice(list) / structs + // slice(list) / pointer to structs { app := struct { Birds []*testdata.Bird @@ -248,6 +248,30 @@ func TestReflect2Write(t *testing.T) { write(n, m2, `{"birds":[{"name":"robin","species":{"name":"DC Comics"}}]}`) fc.AssertEqual(t, "DC Comics", app.Birds[0].Species.Name) + // delete + sel, err := b.Root().Find("birds=robin") + fc.RequireEqual(t, nil, err) + fc.RequireEqual(t, true, sel != nil) + fc.RequireEqual(t, nil, sel.Delete()) + fc.AssertEqual(t, 0, len(app.Birds)) + } + // slice(list) / structs + { + app := struct { + Birds []testdata.Bird + }{} + n := nodeutil.ReflectChild(&app) + write(n, m2, `{"birds":[{"name":"robin","species":{"name":"thrush"}}]}`) + if len(app.Birds) != 1 { + t.Fail() + } + fc.AssertEqual(t, "robin", app.Birds[0].Name) + fc.AssertEqual(t, "thrush", app.Birds[0].Species.Name) + + // update + write(n, m2, `{"birds":[{"name":"robin","species":{"name":"DC Comics"}}]}`) + fc.AssertEqual(t, "DC Comics", app.Birds[0].Species.Name) + // delete sel, err := b.Root().Find("birds=robin") fc.RequireEqual(t, nil, err) @@ -531,7 +555,7 @@ func TestCollectionNonStringKey(t *testing.T) { mstr := `module m { namespace ""; prefix ""; - revision 0; + revision 0; list x { key id; leaf id { @@ -540,7 +564,7 @@ func TestCollectionNonStringKey(t *testing.T) { leaf data { type string; } - } + } }` m, err := parser.LoadModuleFromString(nil, mstr) if err != nil {