-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
105 lines (82 loc) · 2.01 KB
/
example_test.go
File metadata and controls
105 lines (82 loc) · 2.01 KB
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
package main_test
import (
"bytes"
"fmt"
"maps"
"github.com/sonalys/gon"
"github.com/sonalys/gon/adapters"
"github.com/sonalys/gon/encoding"
"github.com/sonalys/gon/gonutils"
)
type customNode struct {
input adapters.Node
}
func (node *customNode) Type() adapters.NodeType {
return adapters.NodeTypeExpression
}
func (node *customNode) Scalar() string {
return "customNode"
}
func (node *customNode) Shape() []adapters.KeyNode {
return []adapters.KeyNode{
{Key: "myCustomParam", Node: node.input},
}
}
func (node *customNode) Eval(scope adapters.Scope) adapters.Value {
valued := node.input.Eval(scope)
fmt.Printf("got: %v\n", valued.Value())
return gon.Literal(true)
}
func (node *customNode) Register(codex adapters.Codex) error {
return codex.Register(node.Scalar(), func(args []adapters.KeyNode) (adapters.Node, error) {
orderedArgs, _, err := gonutils.SortArgs(args, "myCustomParam")
if err != nil {
return nil, err
}
return &customNode{
input: orderedArgs["myCustomParam"],
}, nil
})
}
var (
// Ensure these constraints are met if you want your node to encode/decode properly.
_ adapters.SerializableNode = &customNode{}
)
func Example_customNode() {
myExpression := gon.If(&customNode{input: gon.Literal("my-param")}, gon.Literal("works!"))
buffer := bytes.NewBuffer(make([]byte, 0))
err := encoding.HumanEncode(buffer, myExpression)
if err != nil {
panic(err)
}
customCodex := maps.Clone(encoding.DefaultExpressionCodex)
err = customCodex.AutoRegister(&customNode{})
if err != nil {
panic(err)
}
decodedNode, err := encoding.Decode(buffer.Bytes(), customCodex)
if err != nil {
panic(err)
}
scope, err := gon.
NewScope().
WithValues(gon.Values{
"var": gon.Literal("my-var"),
})
if err != nil {
panic(err)
}
fmt.Println(buffer.String())
value, err := scope.Compute(decodedNode)
if err != nil {
panic(err)
}
fmt.Println(value)
//Output:
// if(
// condition: customNode(myCustomParam: "my-param"),
// then: "works!"
// )
// got: my-param
// works!
}