irongit

A series of universal tools for go projects.

golib/querytools/orderby.go
58 lines1.4 KBGo
1package querytools
2
3import (
4 "fmt"
5 "strings"
6
7 "github.com/gin-gonic/gin"
8)
9
10type OrderByField struct {
11 Dir string
12 Field string
13}
14
15type OrderBy struct {
16 Fields []OrderByField
17}
18
19func (ob OrderBy) SqlStmt() string {
20 if len(ob.Fields) == 0 {
21 return ""
22 }
23 stmt := "ORDER BY "
24 for _, field := range ob.Fields {
25 stmt += fmt.Sprintf("%s %s,", field.Field, field.Dir)
26 }
27 return stmt[:len(stmt)-1]
28}
29
30func (ob *OrderBy) Append(field OrderByField) {
31 ob.Fields = append(ob.Fields, field)
32}
33
34func OrderByFromString(allowed_fields map[string]struct{}, s string) OrderBy {
35 ob := OrderBy{}
36 for raw := range strings.SplitSeq(s, ",") {
37 dir := "ASC"
38 if raw[0] == '-' {
39 raw = raw[1:]
40 dir = "DESC"
41 }
42 if _, exists := allowed_fields[raw]; exists {
43 ob.Append(OrderByField{Field: raw, Dir: dir})
44 }
45 }
46 return ob
47}
48
49// QueryOrderBy returns a direction and field name using default direction and default field to fall back on.
50// Uses order_by query param or def if the query param does not exist.
51// Each field must exist in allowed_fields and a dash (-) implies descending.
52// Returns an OrderBy instance wich has the SqlStmt function.
53func QueryOrderBy(c *gin.Context, allowed_fields map[string]struct{}, def string) OrderBy {
54 if c.Query("order_by") == "" {
55 return OrderByFromString(allowed_fields, def)
56 }
57 return OrderByFromString(allowed_fields, c.Query("order_by"))
58}