Skip to content

Commit

Permalink
elastic: use cty/json marshal
Browse files Browse the repository at this point in the history
  • Loading branch information
dobarx committed Apr 3, 2024
1 parent b8f2413 commit e3eb569
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
2 changes: 1 addition & 1 deletion internal/elastic/data_elastic_security_cases_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func TestReportsDataSourceTestSuite(t *testing.T) {
func (s *ReportsDataSourceTestSuite) SetupSuite() {
s.schema = makeElasticSecurityCasesDataSource(func(url string, apiKey *string) kbclient.Client {
s.storedUrl = url
s.storedApiKey = *&apiKey
s.storedApiKey = apiKey
return s.cli
})
s.ctx = context.Background()
Expand Down
16 changes: 13 additions & 3 deletions internal/elastic/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
es "github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/esapi"
"github.com/zclconf/go-cty/cty"
ctyjson "github.com/zclconf/go-cty/cty/json"

"github.com/blackstork-io/fabric/internal/elastic/kbclient"
"github.com/blackstork-io/fabric/plugin"
Expand Down Expand Up @@ -133,10 +134,19 @@ func search(fn esapi.Search, args cty.Value) (plugin.Data, error) {
}
body := map[string]any{}
if query := args.GetAttr("query"); !query.IsNull() {
body["query"] = query.AsValueMap()
raw, err := ctyjson.Marshal(query, query.Type())
if err != nil {
return nil, fmt.Errorf("failed to marshal query: %s", err)
}
body["query"] = json.RawMessage(raw)

}
if aggs := args.GetAttr("aggs"); !aggs.IsNull() {
body["aggs"] = aggs.AsValueMap()
raw, err := ctyjson.Marshal(aggs, aggs.Type())
if err != nil {
return nil, fmt.Errorf("failed to marshal aggs: %s", err)
}
body["aggs"] = json.RawMessage(raw)
}
if len(body) > 0 {
rawBody, err := json.Marshal(body)
Expand All @@ -147,7 +157,7 @@ func search(fn esapi.Search, args cty.Value) (plugin.Data, error) {
}
if size := args.GetAttr("size"); !size.IsNull() {
n, _ := size.AsBigFloat().Int64()
if n <= 0 {
if n < 0 {
return nil, fmt.Errorf("size must be greater than 0")
}
opts = append(opts, fn.WithSize(int(n)))
Expand Down

0 comments on commit e3eb569

Please sign in to comment.