validate.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package asset
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/opencost/opencost/core/pkg/autocomplete"
  6. "github.com/opencost/opencost/core/pkg/opencost"
  7. )
  8. // ValidateField normalizes and validates an asset autocomplete field name.
  9. func ValidateField(field string) (string, error) {
  10. f := strings.ToLower(field)
  11. switch f {
  12. case "account", "cluster", "name", "provider", "providerid", "type", "assettype", "category":
  13. if f == "assettype" {
  14. return "type", nil
  15. }
  16. return f, nil
  17. }
  18. if f == "label" {
  19. return f, nil
  20. }
  21. if strings.HasPrefix(f, "label:") {
  22. _, labelKey, _ := strings.Cut(field, ":")
  23. return autocomplete.FormatLabelValueField(autocomplete.LabelPrefix, labelKey), nil
  24. }
  25. return "", fmt.Errorf("unrecognized field: %s", field)
  26. }
  27. func ValidateWindow(window opencost.Window) error {
  28. if window.IsOpen() {
  29. return fmt.Errorf("%w: invalid window: %s", autocomplete.ErrBadRequest, window.String())
  30. }
  31. if window.Start() == nil || window.End() == nil {
  32. return fmt.Errorf("%w: invalid window: missing start or end", autocomplete.ErrBadRequest)
  33. }
  34. return nil
  35. }