query.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package utils
  2. import (
  3. "fmt"
  4. "reflect"
  5. "github.com/porter-dev/porter/internal/templater"
  6. "k8s.io/client-go/util/jsonpath"
  7. )
  8. // NewQuery constructs a templater.TemplateReaderQuery by parsing the jsonpath
  9. // query string
  10. func NewQuery(key, query string) (*templater.TemplateReaderQuery, error) {
  11. j := jsonpath.New(key)
  12. j.AllowMissingKeys(true)
  13. err := j.Parse(query)
  14. if err != nil {
  15. return nil, err
  16. }
  17. return &templater.TemplateReaderQuery{
  18. Key: key,
  19. QueryString: query,
  20. Template: j,
  21. }, nil
  22. }
  23. // QueryValues iterates through a map[string]interface{} and executes a query,
  24. // returning a map of the query name to the returned data
  25. func QueryValues(
  26. values map[string]interface{},
  27. queries []*templater.TemplateReaderQuery,
  28. ) (map[string]interface{}, error) {
  29. res := make(map[string]interface{})
  30. // iterate through all registered queries, add to resulting map
  31. for _, query := range queries {
  32. fullResults, err := query.Template.FindResults(values)
  33. if err != nil {
  34. fmt.Printf("query error %s", err)
  35. continue
  36. }
  37. queryRes := make([]reflect.Value, 0)
  38. for ix := range fullResults {
  39. for _, result := range fullResults[ix] {
  40. queryRes = append(queryRes, reflect.ValueOf(result.Interface()))
  41. }
  42. }
  43. res[query.Key] = queryRes
  44. }
  45. return res, nil
  46. }