query.go 1.2 KB

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