filter.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. package qs
  2. import (
  3. "errors"
  4. "net/http"
  5. "net/url"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. )
  10. // Query error.
  11. var (
  12. ErrInvalidFilter = errors.New("invalid filter")
  13. ErrTooManyFilters = errors.New("too many filters")
  14. )
  15. var (
  16. filterRegexp = regexp.MustCompile("^([A-z0-9]+) (eq|neq|gt|gte|lt|lte|in|not in|like|not like) (.+)$")
  17. sliceSeparator = ","
  18. )
  19. // Filter represents a filter as used in, most likely, a database query.
  20. type Filter struct {
  21. Field string `json:"field"` // Field to filter on.
  22. Operator string `json:"operator"` // Filter operator, e.g. eq, gt...
  23. Value string `json:"value"` // Value to filter by.
  24. }
  25. // BoolSlice retrieves the filter value as a slice of bools.
  26. func (filter Filter) BoolSlice() ([]bool, error) {
  27. values := strings.Split(filter.Value, sliceSeparator)
  28. bools := []bool{}
  29. for _, value := range values {
  30. boolValue, err := strconv.ParseBool(value)
  31. if err != nil {
  32. return nil, err
  33. }
  34. bools = append(bools, boolValue)
  35. }
  36. return bools, nil
  37. }
  38. // BoolValue retrieves the filter value as a bool.
  39. func (filter Filter) BoolValue() (bool, error) {
  40. return strconv.ParseBool(filter.Value)
  41. }
  42. // Float32Slice retrieves the filter value as a slice of float32s.
  43. func (filter Filter) Float32Slice() ([]float32, error) {
  44. values := strings.Split(filter.Value, sliceSeparator)
  45. floats := []float32{}
  46. for _, value := range values {
  47. floatValue, err := strconv.ParseFloat(value, 32)
  48. if err != nil {
  49. return nil, err
  50. }
  51. floats = append(floats, float32(floatValue))
  52. }
  53. return floats, nil
  54. }
  55. // Float32Value retrieves the filter value as a float32.
  56. func (filter Filter) Float32Value() (float32, error) {
  57. value, err := strconv.ParseFloat(filter.Value, 32)
  58. return float32(value), err
  59. }
  60. // Float64Slice retrieves the filter value as a slice of float64s.
  61. func (filter Filter) Float64Slice() ([]float64, error) {
  62. values := strings.Split(filter.Value, sliceSeparator)
  63. floats := []float64{}
  64. for _, value := range values {
  65. floatValue, err := strconv.ParseFloat(value, 64)
  66. if err != nil {
  67. return nil, err
  68. }
  69. floats = append(floats, float64(floatValue))
  70. }
  71. return floats, nil
  72. }
  73. // Float64Value retrieves the filter value as a float64.
  74. func (filter Filter) Float64Value() (float64, error) {
  75. return strconv.ParseFloat(filter.Value, 64)
  76. }
  77. // IntSlice retrieves the filter value as a slice of ints.
  78. func (filter Filter) IntSlice() ([]int, error) {
  79. values := strings.Split(filter.Value, sliceSeparator)
  80. ints := []int{}
  81. for _, value := range values {
  82. intValue, err := strconv.Atoi(value)
  83. if err != nil {
  84. return nil, err
  85. }
  86. ints = append(ints, int(intValue))
  87. }
  88. return ints, nil
  89. }
  90. // IntValue retrieves the filter value as an int.
  91. func (filter Filter) IntValue() (int, error) {
  92. return strconv.Atoi(filter.Value)
  93. }
  94. // StringSlice retrieves the filter value as a slice of strings.
  95. func (filter Filter) StringSlice() ([]string, error) {
  96. strings := strings.Split(filter.Value, sliceSeparator)
  97. return strings, nil
  98. }
  99. // Filters is a slice of Filter structs.
  100. type Filters []Filter
  101. // Field returns a new Filters slice containing only filters for the specified field.
  102. // The original order of filters is preserved.
  103. func (filters Filters) Field(field string) Filters {
  104. ff := Filters{}
  105. for _, filter := range filters {
  106. if filter.Field == field {
  107. ff = append(ff, filter)
  108. }
  109. }
  110. return ff
  111. }
  112. // Fields returns a new Filters slice containing filters for any of the specified fields.
  113. // The original order of filters is preserved.
  114. func (filters Filters) Fields(fields ...string) Filters {
  115. ff := Filters{}
  116. for _, filter := range filters {
  117. for _, field := range fields {
  118. if filter.Field == field {
  119. ff = append(ff, filter)
  120. }
  121. }
  122. }
  123. return ff
  124. }
  125. // HasField returns true if the Filters slice includes any filters for the specified field.
  126. func (filters Filters) HasField(field string) bool {
  127. for _, filter := range filters {
  128. if filter.Field == field {
  129. return true
  130. }
  131. }
  132. return false
  133. }
  134. // ReadFiltersOptions configures the behaviour of ReadFilters.
  135. type ReadFiltersOptions struct {
  136. Key string // Query string key. The default value is "filter"
  137. MaxFilters int // If this is > 0, a maximum number of filters is imposed
  138. }
  139. // ReadFilters parses URL values into a slice of filters.
  140. // This function returns nil if no filters are found.
  141. func ReadFilters(values url.Values, opt *ReadFiltersOptions) (Filters, error) {
  142. opt = initFiltersOptions(opt)
  143. if !values.Has(opt.Key) {
  144. return nil, nil
  145. }
  146. if opt.MaxFilters > 0 && len(values[opt.Key]) > opt.MaxFilters {
  147. return nil, ErrTooManyFilters
  148. }
  149. filters := Filters{}
  150. for _, filterStr := range values[opt.Key] {
  151. match := filterRegexp.FindStringSubmatch(filterStr)
  152. if match == nil {
  153. return nil, ErrInvalidFilter
  154. }
  155. filter := Filter{
  156. Field: match[1],
  157. Operator: match[2],
  158. Value: match[3],
  159. }
  160. filters = append(filters, filter)
  161. }
  162. return filters, nil
  163. }
  164. // ReadRequestFilters parses a request's query string into a slice of filters.
  165. // This function returns nil if no filters are found.
  166. func ReadRequestFilters(req *http.Request, opt *ReadFiltersOptions) (Filters, error) {
  167. return ReadFilters(req.URL.Query(), opt)
  168. }
  169. // ReadStringFilters parses a query string literal into a slice of filters.
  170. // This function returns nil if no filters are found.
  171. func ReadStringFilters(qs string, opt *ReadFiltersOptions) (Filters, error) {
  172. values, err := url.ParseQuery(qs)
  173. if err != nil {
  174. return nil, err
  175. }
  176. return ReadFilters(values, opt)
  177. }
  178. func initFiltersOptions(opt *ReadFiltersOptions) *ReadFiltersOptions {
  179. def := &ReadFiltersOptions{
  180. Key: "filter",
  181. }
  182. if opt != nil {
  183. if len(opt.Key) > 0 {
  184. def.Key = opt.Key
  185. }
  186. if opt.MaxFilters > def.MaxFilters {
  187. def.MaxFilters = opt.MaxFilters
  188. }
  189. }
  190. return def
  191. }