Skip to content

Commit ba09e57

Browse files
authored
Merge pull request #2313 from ripienaar/2312
(#2312) Support a query on JSON data in kv watcher
2 parents 8d85f91 + e4c3a84 commit ba09e57

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

aagent/watchers/kvwatcher/kv.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import (
1717

1818
"github.com/google/go-cmp/cmp"
1919
"github.com/nats-io/nats.go"
20+
"github.com/tidwall/gjson"
2021

2122
"github.com/choria-io/ccm/hiera"
2223
"github.com/choria-io/go-choria/aagent/model"
@@ -59,6 +60,7 @@ type properties struct {
5960
RepublishTrigger string `mapstructure:"republish_trigger"`
6061
HieraConfig bool `mapstructure:"hiera_config"`
6162
StoreKey string `mapstructure:"store_key"`
63+
Query string `mapstructure:"query"`
6264
}
6365

6466
type Watcher struct {
@@ -337,6 +339,15 @@ func (w *Watcher) parseValue(val []byte) (any, error) {
337339
}
338340
}
339341

342+
if w.properties.Query != "" {
343+
j, err := json.Marshal(parsedValue)
344+
if err != nil {
345+
return nil, fmt.Errorf("could not marshal data for query: %w", err)
346+
}
347+
348+
res := gjson.GetBytes(j, w.properties.Query)
349+
parsedValue = res.Value()
350+
}
340351
} else if bytes.HasPrefix(v, []byte("[")) && bytes.HasSuffix(v, []byte("]")) {
341352
parsedValue = []any{}
342353
err := json.Unmarshal(v, &parsedValue)

aagent/watchers/kvwatcher/kv_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,14 @@ var _ = Describe("AAgent/Watchers/KvWatcher", func() {
8383
Expect(err).ToNot(HaveOccurred())
8484
})
8585

86+
It("Should support data queries", func() {
87+
w.properties.Query = "spec"
88+
kve.EXPECT().Value().Return([]byte("{\"spec\": \"foo\"}")).MinTimes(1)
89+
machine.EXPECT().DataPut("machines", "foo").Return(nil).Times(1)
90+
_, err := w.poll()
91+
Expect(err).ToNot(HaveOccurred())
92+
})
93+
8694
It("Should handle a leading and trailing unicode whitespace", func() {
8795
kve.EXPECT().Value().Return([]byte("\n \t{\"spec\": \"foo\"}\t \n")).MinTimes(1)
8896
machine.EXPECT().DataPut("machines", map[string]any{"spec": "foo"}).Return(nil).Times(1)

0 commit comments

Comments
 (0)