Skip to content

Commit

Permalink
feat (payload) test case for wrong paths
Browse files Browse the repository at this point in the history
  • Loading branch information
pentateu committed May 1, 2020
1 parent aae177a commit b092546
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
13 changes: 8 additions & 5 deletions payload/payload.go
Original file line number Diff line number Diff line change
Expand Up @@ -473,22 +473,22 @@ 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)
}
if isIndexed(s) {
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)
}
Expand All @@ -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
}
Expand Down
20 changes: 20 additions & 0 deletions payload/payload_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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("<nil>"))

Expect(p.Get("address.wrong").Exists()).Should(BeFalse())

Expect(p.Get("address.options[10].label").Exists()).Should(BeFalse())
})
})

0 comments on commit b092546

Please sign in to comment.