-
Notifications
You must be signed in to change notification settings - Fork 3
/
decision.go
51 lines (45 loc) · 1.19 KB
/
decision.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
package trigger
import (
"github.com/google/cel-go/cel"
"github.com/pkg/errors"
)
var (
ErrDecisionDenied = errors.New("trigger: evaluation = false")
ErrEmptyExpressions = errors.New("trigger: empty expressions")
)
// Decision is used to evaluate boolean expressions
type Decision struct {
program cel.Program
expression string
}
// NewDecision creates a new Decision with the given boolean CEL expressions
func NewDecision(expression string) (*Decision, error) {
if expression == "" {
return nil, ErrEmptyExpressions
}
program, err := globalEnv.Program(expression)
if err != nil {
return nil, err
}
return &Decision{
program: program,
expression: expression,
}, nil
}
// Eval evaluates the boolean CEL expressions against the Mapper
func (n *Decision) Eval(data map[string]interface{}) error {
out, _, err := n.program.Eval(map[string]interface{}{
"this": data,
})
if err != nil {
return errors.Wrapf(err, "trigger: failed to evaluate decision (%s)", n.expression)
}
if val, ok := out.Value().(bool); !ok || !val {
return ErrDecisionDenied
}
return nil
}
// Expressions returns the decsions raw expression
func (e *Decision) Expression() string {
return e.expression
}