-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort.go
52 lines (48 loc) · 1.16 KB
/
sort.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
package common
import "strings"
// SortConfiguration is the configuration of Sort.
type SortConfiguration struct {
Allowed []string // Allowed parameters
Default string
DefaultSorting string // if empty, DESC
Table string
}
// Sort allows the request to modify how the query is sorted.
func Sort(md MethodData, config SortConfiguration) string {
if config.DefaultSorting == "" {
config.DefaultSorting = "DESC"
}
if config.Table != "" {
config.Table += "."
}
var sortBy string
for _, s := range md.Ctx.Request.URI().QueryArgs().PeekMulti("sort") {
sortParts := strings.Split(strings.ToLower(b2s(s)), ",")
if contains(config.Allowed, sortParts[0]) {
if sortBy != "" {
sortBy += ", "
}
sortBy += config.Table + sortParts[0] + " "
if len(sortParts) > 1 && contains([]string{"asc", "desc"}, sortParts[1]) {
sortBy += sortParts[1]
} else {
sortBy += config.DefaultSorting
}
}
}
if sortBy == "" {
sortBy = config.Default
}
if sortBy == "" {
return ""
}
return "ORDER BY " + sortBy
}
func contains(a []string, s string) bool {
for _, el := range a {
if s == el {
return true
}
}
return false
}