forked from linode/linodego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
comparison.go
97 lines (77 loc) · 2.01 KB
/
comparison.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
package linodego
import (
"encoding/json"
)
type FilterOperator string
const (
Eq FilterOperator = "+eq"
Neq FilterOperator = "+neq"
Gt FilterOperator = "+gt"
Gte FilterOperator = "+gte"
Lt FilterOperator = "+lt"
Lte FilterOperator = "+lte"
Contains FilterOperator = "+contains"
Ascending = "asc"
Descending = "desc"
)
type FilterNode interface {
Key() string
JSONValueSegment() interface{}
}
type Filter struct {
// Operator is the logic for all Children nodes ("+and"/"+or")
Operator string
Children []FilterNode
// OrderBy is the field you want to order your results by (ex: "+order_by": "class")
OrderBy string
// Order is the direction in which to order the results ("+order": "asc"/"desc")
Order string
}
func (f *Filter) AddField(op FilterOperator, key string, value interface{}) {
f.Children = append(f.Children, &Comp{key, op, value})
}
func (f *Filter) MarshalJSON() ([]byte, error) {
result := make(map[string]interface{})
if f.OrderBy != "" {
result["+order_by"] = f.OrderBy
}
if f.Order != "" {
result["+order"] = f.Order
}
if f.Operator == "" {
for _, c := range f.Children {
result[c.Key()] = c.JSONValueSegment()
}
return json.Marshal(result)
}
fields := make([]map[string]interface{}, len(f.Children))
for i, c := range f.Children {
fields[i] = map[string]interface{}{
c.Key(): c.JSONValueSegment(),
}
}
result[f.Operator] = fields
return json.Marshal(result)
}
type Comp struct {
Column string
Operator FilterOperator
Value interface{}
}
func (c *Comp) Key() string {
return c.Column
}
func (c *Comp) JSONValueSegment() interface{} {
if c.Operator == Eq {
return c.Value
}
return map[string]interface{}{
string(c.Operator): c.Value,
}
}
func Or(order string, orderBy string, nodes ...FilterNode) *Filter {
return &Filter{"+or", nodes, orderBy, order}
}
func And(order string, orderBy string, nodes ...FilterNode) *Filter {
return &Filter{"+and", nodes, orderBy, order}
}