From b092546776be0c54a7466ba1161bc3fe1777b343 Mon Sep 17 00:00:00 2001 From: Rafael Date: Fri, 1 May 2020 17:30:46 +1200 Subject: [PATCH] feat (payload) test case for wrong paths --- payload/payload.go | 13 ++++++++----- payload/payload_test.go | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/payload/payload.go b/payload/payload.go index e32a2be1..802221ac 100644 --- a/payload/payload.go +++ b/payload/payload.go @@ -473,7 +473,7 @@ func (p *RawPayload) Get(s string, defaultValue ...interface{}) moleculer.Payloa //check if is a path of key if isPath(s) { if defaultValue != nil { - return p.getPath(s, defaultValue) + return p.getPath(s, defaultValue...) } return p.getPath(s) } @@ -481,14 +481,14 @@ func (p *RawPayload) Get(s string, defaultValue ...interface{}) moleculer.Payloa k, index := splitIndex(s) var v moleculer.Payload if defaultValue != nil { - v = p.getKey(k, defaultValue) + v = p.getKey(k, defaultValue...) } else { v = p.getKey(k) } return v.At(index) } if defaultValue != nil { - return p.getKey(s, defaultValue) + return p.getKey(s, defaultValue...) } return p.getKey(s) } @@ -498,10 +498,13 @@ func (p *RawPayload) Get(s string, defaultValue ...interface{}) moleculer.Payloa func (p *RawPayload) getPath(path string, defaultValue ...interface{}) moleculer.Payload { parts := strings.Split(path, ".") k := parts[0] - v := p.Get(k, defaultValue) + v := p.Get(k, defaultValue...) for i := 1; i < len(parts); i++ { + if v == nil { + return New(nil) + } k = parts[i] - v = v.Get(k, defaultValue) + v = v.Get(k, defaultValue...) } return v } diff --git a/payload/payload_test.go b/payload/payload_test.go index c5d765be..3d0c6f91 100644 --- a/payload/payload_test.go +++ b/payload/payload_test.go @@ -375,4 +375,24 @@ var _ = Describe("Payload", func() { Expect(p.Get("address.options[0].label").String()).Should(Equal("item 1")) Expect(p.Get("address.options[1].label").String()).Should(Equal("item 2")) }) + It("should deal field paths name.subname...", func() { + p := New(M{ + "address": M{ + "street": "jonny ave", + "options": []M{ + M{ + "label": "item 1", + }, + }, + }, + }) + Expect(p.Get("address.street").String()).Should(Equal("jonny ave")) + + Expect(p.Get("wrong.path").Exists()).Should(BeFalse()) + Expect(p.Get("wrong.path").String()).Should(Equal("")) + + Expect(p.Get("address.wrong").Exists()).Should(BeFalse()) + + Expect(p.Get("address.options[10].label").Exists()).Should(BeFalse()) + }) })