-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsort_builder.go
104 lines (90 loc) · 1.66 KB
/
sort_builder.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package mongodata
import (
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Sort int
const (
SortAsc Sort = 1
SortNone Sort = 0
SortDesc Sort = -1
)
type SortBuilder struct {
data []primitive.E
limit int
skip int
}
// TODO: Rename this
func NewSort() *SortBuilder {
return &SortBuilder{}
}
func (sb *SortBuilder) SetLimit(limit int) *SortBuilder {
sb.limit = limit
return sb
}
func (sb *SortBuilder) SetSkip(skip int) *SortBuilder {
sb.skip = skip
return sb
}
func (sb *SortBuilder) Asc(key string) *SortBuilder {
sb.data = append(sb.data, primitive.E{
Key: key,
Value: 1,
})
return sb
}
func (sb *SortBuilder) Desc(key string) *SortBuilder {
sb.data = append(sb.data, primitive.E{
Key: key,
Value: -1,
})
return sb
}
func (sb *SortBuilder) IfAsc(key string, test bool) *SortBuilder {
if test {
sb.data = append(sb.data, primitive.E{
Key: key,
Value: 1,
})
}
return sb
}
func (sb *SortBuilder) IfDesc(key string, test bool) *SortBuilder {
if test {
sb.data = append(sb.data, primitive.E{
Key: key,
Value: -1,
})
}
return sb
}
func (sb *SortBuilder) IfAscElseDesc(key string, test bool) *SortBuilder {
if test {
sb.data = append(sb.data, primitive.E{
Key: key,
Value: 1,
})
} else {
sb.data = append(sb.data, primitive.E{
Key: key,
Value: -1,
})
}
return sb
}
func (sb *SortBuilder) Build() *options.FindOptions {
if sb == nil {
return options.Find()
}
o := options.Find()
if sb.data != nil {
o = o.SetSort(sb.data)
}
if sb.limit != 0 {
o = o.SetLimit(int64(sb.limit))
}
if sb.skip != 0 {
o = o.SetSkip(int64(sb.skip))
}
return o
}