-
Notifications
You must be signed in to change notification settings - Fork 2
/
sort.go
69 lines (57 loc) · 1.04 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package rsql
import (
"errors"
"fmt"
"net/url"
"strings"
)
type Direction int
const (
Asc Direction = iota
Desc
)
// Sort :
type Sort struct {
Field string
Direction Direction
}
func (p *RSQL) parseSort(values map[string]string, params *Params) error {
val, ok := values[p.SortTag]
delete(values, p.SortTag)
if !ok || len(val) < 1 {
return nil
}
paths := strings.Split(val, ",")
for _, v := range paths {
v = strings.TrimSpace(v)
if len(v) == 0 {
return errors.New("rsql: invalid sort")
}
v, err := url.QueryUnescape(v)
if err != nil {
return err
}
dir := Asc
desc := v[0] == '-'
if desc {
v = v[1:]
dir = Desc
}
f, ok := p.codec.Names[v]
if !ok {
return fmt.Errorf("rsql: invalid field %q to sort", v)
}
if _, ok := f.Tag.Lookup("sort"); !ok {
return fmt.Errorf("rsql: field %q is not allow to sort", v)
}
name := f.Name
if v, ok := f.Tag.Lookup("column"); ok {
name = v
}
params.Sorts = append(params.Sorts, Sort{
Field: name,
Direction: dir,
})
}
return nil
}