/
filtering.go
88 lines (75 loc) · 2.39 KB
/
filtering.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package middleware
import (
"fmt"
"strings"
"github.com/RedHatInsights/sources-api-go/util"
"github.com/labstack/echo/v4"
)
var BadQueryParams = []string{"limit", "offset", "sort_by"}
func SortAndFilter(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
filters, err := parseFilter(c)
if err != nil {
return util.NewErrBadRequest(err)
}
if sort := parseSorting(c); sort != nil {
filters = append(filters, *sort)
}
c.Set("filters", filters)
return next(c)
}
}
func parseFilter(c echo.Context) ([]util.Filter, error) {
f := make([]util.Filter, 0)
for key, values := range c.QueryParams() {
if strings.HasPrefix(key, "filter") {
matches := util.FilterRegex.FindAllStringSubmatch(key, -1)
filter := util.Filter{}
if len(matches) < 2 {
return nil, fmt.Errorf("filter")
}
// matching filter[subresource][field][operation]
// we only support filtering on source type/application type
if matches[1][0] == "source_type" || matches[1][0] == "application_type" {
filter = util.Filter{
Subresource: matches[1][0],
Name: matches[2][0],
Value: values,
}
// this will only be present if the user used a operation. it
// defaults to "" which we use as eq
if len(matches) == 4 {
filter.Operation = matches[3][0]
}
} else {
// matching filter[field][operation]
filter = util.Filter{Name: matches[1][0], Value: values}
// this will only be present if the user used a operation. it
// defaults to "" which we use as eq
if len(matches) == 3 {
filter.Operation = matches[2][0]
}
}
f = append(f, filter)
} else if !util.SliceContainsString(BadQueryParams, key) {
// This is to ensure backward compatibility with the Rails API. Any
// query parameters that do not have `filter` or `sort_by` at the
// beginning need to be treated as "raw" output filters. e.g. if
// someone passes `id=25` we need to support that as equivalent to
// `filter[id]=25`
//
// if the column doesn't exist PG will throw a sqlstate error -
// which is expected.
f = append(f, util.Filter{Name: key, Value: values})
}
}
return f, nil
}
func parseSorting(c echo.Context) *util.Filter {
for k, v := range c.QueryParams() {
if k == "sort_by" {
return &util.Filter{Operation: "sort_by", Value: v}
}
}
return &util.Filter{Operation: "sort_by", Value: []string{"id ASC"}}
}