-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
88 lines (76 loc) · 1.86 KB
/
context.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
package javascript
import (
"github.com/dop251/goja"
"github.com/team-ide/go-tool/javascript/context_map"
"github.com/team-ide/go-tool/util"
"go.uber.org/zap"
)
func NewContext() map[string]interface{} {
baseContext := map[string]interface{}{}
for _, module := range context_map.ModuleList {
data := map[string]interface{}{}
baseContext[module.Name] = data
for _, funcInfo := range module.FuncList {
data[funcInfo.Name] = funcInfo.Func
}
}
return baseContext
}
type Script struct {
dataContext map[string]interface{}
vm *goja.Runtime
}
func (this_ *Script) Set(name string, value interface{}) (err error) {
this_.dataContext[name] = value
err = this_.vm.Set(name, value)
if err != nil {
return
}
return
}
func (this_ *Script) GetScriptValue(script string) (value interface{}, err error) {
if script == "" {
value = ""
return
}
var scriptValue goja.Value
if scriptValue, err = this_.vm.RunString(script); err != nil {
util.Logger.Error("表达式执行异常", zap.Any("script", script), zap.Error(err))
return
}
value = scriptValue.Export()
return
}
func (this_ *Script) GetStringScriptValue(script string) (value string, err error) {
var scriptValue interface{}
scriptValue, err = this_.GetScriptValue(script)
if scriptValue != nil {
value = util.GetStringValue(scriptValue)
return
}
return
}
func NewScript() (script *Script, err error) {
return NewScriptByParent(nil)
}
func NewScriptByParent(parent *Script) (script *Script, err error) {
script = &Script{}
script.vm = goja.New()
script.dataContext = make(map[string]interface{})
scriptContext := NewContext()
for key, value := range scriptContext {
err = script.vm.Set(key, value)
if err != nil {
return
}
}
if parent != nil {
for key, value := range parent.dataContext {
err = script.Set(key, value)
if err != nil {
return
}
}
}
return
}