query.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package utils
  2. import (
  3. "github.com/itchyny/gojq"
  4. "github.com/porter-dev/porter/internal/templater"
  5. )
  6. // NewQuery constructs a templater.TemplateReaderQuery by parsing the jsonpath
  7. // query string
  8. func NewQuery(key, query string) (*templater.TemplateReaderQuery, error) {
  9. jquery, err := gojq.Parse(query)
  10. if err != nil {
  11. return nil, err
  12. }
  13. return &templater.TemplateReaderQuery{
  14. Key: key,
  15. QueryString: query,
  16. Template: jquery,
  17. }, nil
  18. }
  19. // QueryValues iterates through a map[string]interface{} and executes a query,
  20. // returning a map of the query name to the returned data
  21. func QueryValues(
  22. values map[string]interface{},
  23. queries []*templater.TemplateReaderQuery,
  24. ) (map[string]interface{}, error) {
  25. res := make(map[string]interface{})
  26. // iterate through all registered queries, add to resulting map
  27. for _, query := range queries {
  28. iter := query.Template.Run(values)
  29. queryRes := make([]interface{}, 0)
  30. for {
  31. v, ok := iter.Next()
  32. if !ok {
  33. break
  34. }
  35. if err, ok := v.(error); ok {
  36. return nil, err
  37. }
  38. queryRes = append(queryRes, v)
  39. }
  40. res[query.Key] = queryRes
  41. }
  42. return res, nil
  43. }