forked from mfcochauxlaberge/jsonapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilter_query.go
More file actions
74 lines (64 loc) · 1.32 KB
/
filter_query.go
File metadata and controls
74 lines (64 loc) · 1.32 KB
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
package jsonapi
import (
"encoding/json"
)
// Condition ...
type Condition struct {
Field string `json:"f"`
Op string `json:"o"`
Val interface{} `json:"v"`
Col string `json:"c"`
}
// cnd ...
type cnd struct {
Field string `json:"f"`
Op string `json:"o"`
Val json.RawMessage `json:"v"`
Col string `json:"c"`
}
// UnmarshalJSON ...
func (c *Condition) UnmarshalJSON(data []byte) error {
tmpCnd := cnd{}
err := json.Unmarshal(data, &tmpCnd)
if err != nil {
return err
}
c.Field = tmpCnd.Field
c.Op = tmpCnd.Op
c.Col = tmpCnd.Col
if tmpCnd.Op == "and" || tmpCnd.Op == "or" {
c.Field = ""
cnds := []Condition{}
err := json.Unmarshal(tmpCnd.Val, &cnds)
if err != nil {
return err
}
c.Val = cnds
} else if tmpCnd.Op == "=" ||
tmpCnd.Op == "!=" ||
tmpCnd.Op == "<" ||
tmpCnd.Op == "<=" ||
tmpCnd.Op == ">" ||
tmpCnd.Op == ">=" {
err := json.Unmarshal(tmpCnd.Val, &(c.Val)) // TODO parenthesis needed?
if err != nil {
return err
}
}
return nil
}
// MarshalJSON ...
func (c *Condition) MarshalJSON() ([]byte, error) {
payload := map[string]interface{}{}
if c.Field != "" {
payload["f"] = c.Field
}
if c.Op != "" {
payload["o"] = c.Op
}
payload["v"] = c.Val
if c.Col != "" {
payload["c"] = c.Col
}
return json.Marshal(payload)
}