forked from dop251/goja
/
runtime_options.go
60 lines (54 loc) · 1.68 KB
/
runtime_options.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
package goja
import (
"reflect"
"github.com/powerpuffpenguin/goja/loop"
)
var defaultOptions = options{}
type Option interface {
apply(*options)
}
type Caller interface {
// Before the native function is called, calling Before can be used as an interceptor, and returning errr will panic(r.NewGoError(err))
Before(r *Runtime, call *FunctionCall) (err error)
// Control how to call native functions, for example, you can start a new goroutine to call native functions
Call(r *Runtime, callSlice bool, callable reflect.Value, in []reflect.Value) (out []reflect.Value, err error)
// Called before returning the function call result out to js, used to convert the return value to js or filter the function return value
After(r *Runtime, out []reflect.Value) (result Value, err error)
}
type CallerFactory interface {
// Get a Caller
Get() Caller
// If you want to reuse, you can implement the Put function, otherwise save it as an empty implementation.
Put(caller Caller)
}
type options struct {
callerFactory CallerFactory
scheduler loop.Scheduler
fieldGetter func(reflect.Value) reflect.Value
}
type funcOption struct {
f func(*options)
}
func (fdo *funcOption) apply(do *options) {
fdo.f(do)
}
func newFuncOption(f func(*options)) *funcOption {
return &funcOption{
f: f,
}
}
func WithCallerFactory(callerFactory CallerFactory) Option {
return newFuncOption(func(o *options) {
o.callerFactory = callerFactory
})
}
func WithScheduler(scheduler loop.Scheduler) Option {
return newFuncOption(func(o *options) {
o.scheduler = scheduler
})
}
func WithFieldGetter(getter func(reflect.Value) reflect.Value) Option {
return newFuncOption(func(o *options) {
o.fieldGetter = getter
})
}