conditions.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. type ConditionOperator string
  31. const (
  32. OperatorEqual = "="
  33. OperatorNotEqual = "!="
  34. OperatorMore = ">"
  35. OperatorLess = "<"
  36. OperatorMoreEqual = ">="
  37. OperatorLessEqual = "<="
  38. OperatorLike = "like"
  39. )
  40. func (s ConditionOperator) IsValid() bool {
  41. switch s {
  42. case OperatorEqual:
  43. case OperatorNotEqual:
  44. case OperatorMore:
  45. case OperatorLess:
  46. case OperatorMoreEqual:
  47. case OperatorLessEqual:
  48. case OperatorLike:
  49. default:
  50. return false
  51. }
  52. return true
  53. }
  54. //////////////////////////////////////////////////////////////////////////////
  55. const (
  56. LogicEmpty = ""
  57. LogicOR = "or"
  58. LogicAND = "and"
  59. )
  60. type ConditionLogic string
  61. func (s ConditionLogic) IsValid() bool {
  62. switch s {
  63. case LogicEmpty:
  64. case LogicOR:
  65. case LogicAND:
  66. default:
  67. return false
  68. }
  69. return true
  70. }
  71. //////////////////////////////////////////////////////////////////////////////
  72. type Condition struct {
  73. Field string
  74. Logic ConditionLogic
  75. Operator ConditionOperator
  76. Value any
  77. }
  78. func (s *Condition) IsValid() bool {
  79. return len(s.Field) > 0 && s.Logic.IsValid() && s.Operator.IsValid()
  80. }