conditions.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package rest
  2. import (
  3. "fmt"
  4. "git.ali33.ru/fcg-xvii/go-tools/json"
  5. )
  6. func parseCondition(m json.Map, index int) (*Condition, error) {
  7. errPrefix := func(errData string) error {
  8. return fmt.Errorf("[%v]: %s", index, errData)
  9. }
  10. cond := Condition{
  11. Field: m.String("field", ""),
  12. Logic: ConditionLogic(m.String("logic", "")),
  13. Operator: ConditionOperator(m.String("operator", "")),
  14. Value: m["value"],
  15. }
  16. if !cond.IsValid() {
  17. if len(cond.Field) == 0 {
  18. return nil, errPrefix("empty field name")
  19. } else if !cond.Operator.IsValid() {
  20. return nil, errPrefix(fmt.Sprintf("unexpected operator [%s]", cond.Operator))
  21. } else if !cond.Operator.IsValid() {
  22. return nil, errPrefix(fmt.Sprintf("unexpected logic [%s]", cond.Logic))
  23. } else {
  24. return nil, errPrefix("unexpected error")
  25. }
  26. }
  27. return &cond, nil
  28. }
  29. //////////////////////////////////////////////////////////////////////////////
  30. // swagger:model ConditionOperator
  31. type ConditionOperator string
  32. const (
  33. OperatorEqual = "="
  34. OperatorNotEqual = "!="
  35. OperatorMore = ">"
  36. OperatorLess = "<"
  37. OperatorMoreEqual = ">="
  38. OperatorLessEqual = "<="
  39. OperatorLike = "like"
  40. )
  41. func (s ConditionOperator) IsValid() bool {
  42. switch s {
  43. case OperatorEqual:
  44. case OperatorNotEqual:
  45. case OperatorMore:
  46. case OperatorLess:
  47. case OperatorMoreEqual:
  48. case OperatorLessEqual:
  49. case OperatorLike:
  50. default:
  51. return false
  52. }
  53. return true
  54. }
  55. //////////////////////////////////////////////////////////////////////////////
  56. const (
  57. LogicEmpty = ""
  58. LogicOR = "or"
  59. LogicAND = "and"
  60. )
  61. // swagger:model ConditionLogic
  62. type ConditionLogic string
  63. func (s ConditionLogic) IsValid() bool {
  64. switch s {
  65. case LogicEmpty:
  66. case LogicOR:
  67. case LogicAND:
  68. default:
  69. return false
  70. }
  71. return true
  72. }
  73. //////////////////////////////////////////////////////////////////////////////
  74. // swagger:model Condition
  75. type Condition struct {
  76. Field string
  77. Logic ConditionLogic
  78. Operator ConditionOperator
  79. Value any
  80. }
  81. func (s *Condition) IsValid() bool {
  82. return len(s.Field) > 0 && s.Logic.IsValid() && s.Operator.IsValid()
  83. }