-
Notifications
You must be signed in to change notification settings - Fork 4
/
op_dataaccess.go
79 lines (70 loc) · 1.5 KB
/
op_dataaccess.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
package jsonlogic
import (
"strconv"
"strings"
)
type opVar struct{}
type opVarStrictEqual struct{}
func (opVar) Operate(applier LogicApplier, data DataType, params []RuleType) (DataType, error) {
// No params, return whole data
if len(params) == 0 {
return data, nil
}
key, err := applier.Apply(params[0], data)
if err != nil {
return nil, err
}
var keyList []string
notFound := false
switch key := key.(type) {
case string:
keyList = strings.Split(key, ".")
case float64:
keyList = []string{strconv.FormatFloat(key, 'f', -1, 64)}
default:
keyList = nil
notFound = true
}
var d interface{} = data
for _, key := range keyList {
if notFound {
break
}
switch dv := d.(type) {
case map[string]interface{}:
if v, ok := dv[key]; ok {
d = v
} else {
notFound = true
}
case []interface{}:
if kv, err := strconv.ParseUint(key, 10, 64); err == nil && int(kv) < len(dv) {
d = dv[kv]
} else {
notFound = true
}
}
}
if notFound {
if len(params) >= 2 {
d, err = applier.Apply(params[1], data)
if err != nil {
return nil, err
}
} else {
d = nil
}
}
return d, nil
}
func (opVarStrictEqual) Operate(applier LogicApplier, data DataType, params []RuleType) (DataType, error) {
if len(params) < 2 {
return nil, nil
}
result, err := (opVar{}).Operate(applier, data, []RuleType{params[0]})
if err != nil {
return nil, err
}
result, err = (opStrictEqual{}).Operate(applier, data, []RuleType{result, params[1]})
return result, err
}