-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort.go
52 lines (40 loc) · 819 Bytes
/
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 graphpg
import (
"strings"
"github.com/go-pg/pg/orm"
)
// BuildPagination adds to the query a limit offset and the total number of records.
func BuildPagination(query *orm.Query, sort string, limit, offset int) (*orm.Query, int, error) {
var (
tmp string
result []string
count int
)
sortItem := strings.Split(sort, ",")
for _, item := range sortItem {
if strings.HasPrefix(item, "-") {
columnName := item
tmp = columnName[1:] + " DESC"
} else {
tmp = item
}
result = append(result, tmp)
}
for _, srt := range result {
if len(srt) == 0 {
continue
}
query.Order(srt)
}
count, err := query.Count()
if err != nil {
return query, count, err
}
if limit > 0 {
query.Limit(limit)
}
if offset > 0 {
query.Offset(offset)
}
return query, count, nil
}