forked from diegoholiveira/jsonlogic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vars.go
139 lines (104 loc) · 2.32 KB
/
vars.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package jsonlogic
import (
"encoding/json"
"strconv"
"strings"
)
func solveVars(values, data interface{}) interface{} {
if isMap(values) {
logic := map[string]interface{}{}
for key, value := range values.(map[string]interface{}) {
if key == "var" {
if isString(value) && (value == "" || strings.HasPrefix(value.(string), ".")) {
logic["var"] = value
continue
}
val := getVar(value, data)
if val != nil {
return val
}
logic["var"] = value
} else {
logic[key] = solveVars(value, data)
}
}
return interface{}(logic)
}
if isSlice(values) {
logic := []interface{}{}
for _, value := range values.([]interface{}) {
logic = append(logic, solveVars(value, data))
}
return logic
}
return values
}
func getVar(value, data interface{}) interface{} {
if value == nil {
return data
}
if isString(value) && toString(value) == "" {
return data
}
if isNumber(value) {
value = toString(value)
}
var _default interface{}
if isSlice(value) { // syntax sugar
v := value.([]interface{})
if len(v) == 0 {
return data
}
if len(v) == 2 {
_default = v[1]
}
value = v[0].(string)
}
if data == nil {
return _default
}
parts := strings.Split(value.(string), ".")
var _value interface{}
for _, part := range parts {
if part == "" {
continue
}
if isMap(data) {
_value = data.(map[string]interface{})[part]
}
if isSlice(data) {
pos := int(toNumber(part))
container := data.([]interface{})
if pos >= len(container) {
return _default
}
_value = container[pos]
}
if _value == nil {
return _default
}
if isPrimitive(_value) {
continue
}
data = _value
}
return _value
}
func solveVarsBackToJsonLogic(rule, data interface{}) (json.RawMessage, error) {
ruleMap := rule.(map[string]interface{})
result := make(map[string]interface{})
for operator, values := range ruleMap {
result[operator] = solveVars(values, data)
}
resultJson, err := json.Marshal(result)
if err != nil {
return nil, err
}
// we need to use Unquote due to unicode characters (example \u003e= need to be >=)
// used for prettier json.RawMessage
resultEscaped, err := strconv.Unquote(strings.Replace(strconv.Quote(string(resultJson)), `\\u`, `\u`, -1))
if err != nil {
return nil, err
}
return []byte(resultEscaped), nil
}