query.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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, defaultVal interface{}) (*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. Default: defaultVal,
  17. Template: jquery,
  18. }, nil
  19. }
  20. // QueryValues iterates through a map[string]interface{} and executes a query,
  21. // returning a map of the query name to the returned data
  22. func QueryValues(
  23. values map[string]interface{},
  24. queries []*templater.TemplateReaderQuery,
  25. ) (map[string]interface{}, error) {
  26. res := make(map[string]interface{})
  27. // iterate through all registered queries, add to resulting map
  28. for _, query := range queries {
  29. iter := query.Template.Run(values)
  30. queryRes := make([]interface{}, 0)
  31. for {
  32. v, ok := iter.Next()
  33. if !ok {
  34. break
  35. }
  36. if err, ok := v.(error); ok {
  37. return nil, err
  38. }
  39. if v != nil {
  40. queryRes = append(queryRes, v)
  41. }
  42. }
  43. // if the length of the query result is 0, set to the default value
  44. if len(queryRes) == 0 {
  45. res[query.Key] = []interface{}{query.Default}
  46. } else {
  47. res[query.Key] = queryRes
  48. }
  49. }
  50. return res, nil
  51. }