This repository has been archived on 2022-09-04. You can view files and clone it, but cannot push or open issues or pull requests.
api/utils/sanitize_sort.go

43 lines
947 B
Go
Raw Normal View History

2020-06-04 13:06:32 +00:00
package utils
import (
"regexp"
"strings"
)
var (
sortexprRegex = regexp.MustCompile(`^[\p{L}\_\.]+$`)
)
2020-06-04 13:06:32 +00:00
func SanitizeSortExpression(expr string) string {
trimmed := strings.TrimSpace(expr)
2020-06-04 13:06:32 +00:00
splitted := strings.Split(trimmed, " ")
length := len(splitted)
if length != 2 || !sortexprRegex.Match([]byte(splitted[0])) {
2020-06-04 13:06:32 +00:00
return ""
}
table := ""
column := splitted[0]
if strings.Contains(splitted[0], ".") {
columnAndTable := strings.Split(splitted[0], ".")
table = Underscore(columnAndTable[0]) + "."
column = columnAndTable[1]
}
2020-06-04 13:06:32 +00:00
keyword := "ASC"
if strings.ToUpper(splitted[1]) == "DESC" {
2020-06-04 13:06:32 +00:00
keyword = "DESC"
}
return strings.ToLower(table+Underscore(column)) + " " + keyword
}
func SanitizeSortExpressions(exprs []string) []string {
filtered := []string{}
for _, expr := range exprs {
sanitized := SanitizeSortExpression(expr)
if sanitized != "" {
filtered = append(filtered, sanitized)
}
}
return filtered
2020-06-04 13:06:32 +00:00
}