-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutilities.go
73 lines (67 loc) · 1.48 KB
/
utilities.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
package engine
import (
"encoding/json"
"fmt"
"github.com/dop251/goja"
"strings"
)
func Throw(rt *goja.Runtime, err error) {
if e, ok := err.(*goja.Exception); ok {
panic(e)
}
panic(rt.NewGoError(err))
}
func ToBytes(data any) ([]byte, error) {
switch dt := data.(type) {
case []byte:
return dt, nil
case string:
return []byte(dt), nil
case goja.ArrayBuffer:
return dt.Bytes(), nil
default:
return nil, fmt.Errorf("invalid type %T, expected string, []byte or ArrayBuffer", data)
}
}
func ToString(data any) (string, error) {
switch dt := data.(type) {
case []byte:
return string(dt), nil
case string:
return dt, nil
case goja.ArrayBuffer:
return string(dt.Bytes()), nil
default:
return "", fmt.Errorf("invalid type %T, expected string, []byte or ArrayBuffer", data)
}
}
func IsNullish(v goja.Value) bool {
return v == nil || goja.IsUndefined(v) || goja.IsNull(v)
}
func IsAsyncFunction(rt *goja.Runtime, val goja.Value) bool {
if IsNullish(val) {
return false
}
return val.ToObject(rt).Get("constructor").ToObject(rt).Get("name").String() == "AsyncFunction"
}
func ValueString(v goja.Value) string {
mv, ok := v.(json.Marshaler)
if !ok {
return v.String()
}
b, err := json.Marshal(mv)
if err != nil {
return v.String()
}
return string(b)
}
func ValuesString(args ...goja.Value) string {
var msg strings.Builder
for i := 0; i < len(args); i++ {
if i > 0 {
msg.WriteString(" ")
}
msg.WriteString(ValueString(args[i]))
}
return msg.String()
}