Repository navigation
Expand file tree
/
Copy pathif.go
More file actions
55 lines (48 loc) · 1.46 KB
/
Copy pathif.go
File metadata and controls
55 lines (48 loc) · 1.46 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
package datatemplate
import (
"context"
"strings"
"github.com/demdxx/gocast/v2"
"github.com/pkg/errors"
)
type IfBlock struct {
cond *Program
thenBlock Block
elseBlock Block
}
func NewIfBlock(cond *Program, thenBlock, elseBlock Block) *IfBlock {
return &IfBlock{cond: cond, thenBlock: thenBlock, elseBlock: elseBlock}
}
func NewIfBlockWithContition(ctx context.Context, cond string, thenBlock, elseBlock Block) (Block, error) {
cond = strings.TrimSpace(cond)
if strings.EqualFold(cond, "true") || strings.EqualFold(cond, "1") {
return thenBlock, nil
}
if strings.EqualFold(cond, "false") || strings.EqualFold(cond, "0") || strings.EqualFold(cond, "nil") || strings.EqualFold(cond, "null") {
return elseBlock, nil
}
_cond, err := compileExpr(ctx, cond)
if err != nil {
return nil, errors.Wrap(err, cond)
}
return NewIfBlock(_cond, thenBlock, elseBlock), nil
}
func (b *IfBlock) String() string {
if b.elseBlock == nil {
return "$if: {`$expr`: `" + b.cond.Source.Content() + "`, $then: " + b.thenBlock.String() + "}"
}
return "$if: {`$expr`: `" + b.cond.Source.Content() + "`, $then: " + b.thenBlock.String() + ", $else: " + b.elseBlock.String() + "}"
}
func (b *IfBlock) Emit(ctx context.Context, data map[string]any) (any, error) {
res, err := runExpr(ctx, b.cond, data)
if err != nil {
return nil, err
}
if gocast.Bool(res) {
return b.thenBlock.Emit(ctx, data)
}
if b.elseBlock == nil {
return nil, nil
}
return b.elseBlock.Emit(ctx, data)
}