-
Notifications
You must be signed in to change notification settings - Fork 1
/
ex__get.go
65 lines (53 loc) · 1.25 KB
/
ex__get.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
package expression
import (
"context"
"errors"
"fmt"
contextx "github.com/octohelm/x/context"
)
// Get
//
// Syntax
//
// get("x")
var Get = Register(func(b ExprBuilder) func(fieldName string) Expression {
return func(fieldName string) Expression {
return b.BuildExpression(fieldName)
}
}, &get{})
type get struct {
E
FieldName string
}
func (e *get) Exec(ctx context.Context, in any) (any, error) {
vg := ValueGetterFromContext(ctx)
if vg == nil {
return nil, errors.New("missing value getter")
}
if v, ok := vg.Get(e.FieldName); ok {
return v, nil
}
return nil, fmt.Errorf("missing field %s", e.FieldName)
}
type ValueGetter interface {
Get(name string) (any, bool)
}
type contextValueGetter struct{}
func ValueGetterFunc(g func(name string) (any, bool)) ValueGetter {
return &valueGetterFunc{fn: g}
}
type valueGetterFunc struct {
fn func(name string) (any, bool)
}
func (v *valueGetterFunc) Get(name string) (any, bool) {
return v.fn(name)
}
func WithValueGetter(ctx context.Context, getter ValueGetter) context.Context {
return contextx.WithValue(ctx, contextValueGetter{}, getter)
}
func ValueGetterFromContext(ctx context.Context) ValueGetter {
if vg, ok := ctx.Value(contextValueGetter{}).(ValueGetter); ok {
return vg
}
return nil
}