From fd540a5237b1042973d2e76f988112658f57f311 Mon Sep 17 00:00:00 2001 From: Tobie Morgan Hitchcock Date: Mon, 24 Oct 2016 14:16:33 +0100 Subject: [PATCH] Enable checking for existing and non-null items --- util/data/data.go | 8 ++++++++ util/data/data_test.go | 10 ++++++++++ 2 files changed, 18 insertions(+) diff --git a/util/data/data.go b/util/data/data.go index 074a1403..3cd2aea3 100644 --- a/util/data/data.go +++ b/util/data/data.go @@ -78,6 +78,14 @@ func (d *Doc) Reset(path ...string) (*Doc, error) { return d.Set(nil, path...) } +// Valid checks whether the value at the specified path is nil. +func (d *Doc) Valid(path ...string) bool { + if !d.Exists(path...) { + return false + } + return d.Get(path...).Data() != nil +} + // Array sets the specified path to an array. func (d *Doc) Array(path ...string) (*Doc, error) { return d.Set([]interface{}{}, path...) diff --git a/util/data/data_test.go b/util/data/data_test.go index 70075ee0..6937b3f0 100644 --- a/util/data/data_test.go +++ b/util/data/data_test.go @@ -334,6 +334,16 @@ func TestOperations(t *testing.T) { // ---------------------------------------------------------------------------------------------------- + Convey("Is unset item valid", t, func() { + So(doc.Valid("the.none"), ShouldBeFalse) + }) + + Convey("Is item valid", t, func() { + So(doc.Valid("the.item"), ShouldBeTrue) + }) + + // ---------------------------------------------------------------------------------------------------- + Convey("Can get object keys and vals", t, func() { So(doc.Keys("the.item.object").Data(), ShouldResemble, []interface{}{"enabled"}) So(doc.Vals("the.item.object").Data(), ShouldResemble, []interface{}{false})