Implement value sanitizers on fields
This commit is contained in:
parent
dcd3beeced
commit
cf7b31cbc0
@ -28,6 +28,10 @@ func Sanitizer() *sanitizer {
|
||||
//
|
||||
// Existing data (when updating record) is not yet loaded at this point
|
||||
func (s sanitizer) Run(m *types.Module, vv types.RecordValueSet) (out types.RecordValueSet) {
|
||||
var (
|
||||
exprParser = parser()
|
||||
)
|
||||
|
||||
out = make([]*types.RecordValue, 0, len(vv))
|
||||
|
||||
for _, f := range m.Fields {
|
||||
@ -69,6 +73,13 @@ func (s sanitizer) Run(m *types.Module, vv types.RecordValueSet) (out types.Reco
|
||||
|
||||
kind = strings.ToLower(f.Kind)
|
||||
|
||||
if len(f.Expressions.Sanitizers) > 0 {
|
||||
for _, expr := range f.Expressions.Sanitizers {
|
||||
rval, _ := exprParser.Evaluate(expr, map[string]interface{}{"value": v.Value})
|
||||
v.Value = sanitize(f, rval)
|
||||
}
|
||||
}
|
||||
|
||||
if kind != "string" {
|
||||
// Trim all but string
|
||||
v.Value = strings.TrimSpace(v.Value)
|
||||
|
||||
@ -174,3 +174,38 @@ func Test_sanitizer_Run(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizerExpr(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
kind string
|
||||
expr []string
|
||||
input string
|
||||
output string
|
||||
outref uint64
|
||||
}{
|
||||
{
|
||||
name: "cap numbers",
|
||||
kind: "Number",
|
||||
expr: []string{`value > 42 ? 42 : value`},
|
||||
input: "43",
|
||||
output: "42",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := sanitizer{}
|
||||
m := &types.Module{Fields: types.ModuleFieldSet{&types.ModuleField{Name: "testField", Kind: tt.kind}}}
|
||||
m.Fields.FindByName("testField").Expressions.Sanitizers = tt.expr
|
||||
v := types.RecordValueSet{&types.RecordValue{Name: "testField", Value: tt.input}}
|
||||
o := types.RecordValueSet{&types.RecordValue{Name: "testField", Value: tt.output, Ref: tt.outref}}
|
||||
|
||||
// Need to mark values as updated to trigger sanitization.
|
||||
v.SetUpdatedFlag(true)
|
||||
o.SetUpdatedFlag(true)
|
||||
if sanitized := s.Run(m, v); !reflect.DeepEqual(sanitized, o) {
|
||||
t.Errorf("\ninput value:\n%v\n\nresult of sanitization:\n%v\n\nexpected:\n%v\n", tt.input, sanitized, o)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@ -43,8 +43,8 @@ type (
|
||||
}
|
||||
|
||||
ModuleFieldExpr struct {
|
||||
Value string `json:"value,omitempty"`
|
||||
//Sanitizers []string `json:"sanitizers,omitempty"`
|
||||
Value string `json:"value,omitempty"`
|
||||
Sanitizers []string `json:"sanitizers,omitempty"`
|
||||
//Validators []struct {
|
||||
// Test string `json:"test,omitempty"`
|
||||
// Error string `json:"error,omitempty"`
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user