From b9d2edb3cd781dc37e0ec77730526de2ecd59622 Mon Sep 17 00:00:00 2001 From: Onur Cinar Date: Fri, 27 Dec 2024 07:44:26 -0800 Subject: [PATCH] Register maker is added. (#149) # Describe Request Register maker is added. # Change Type New code. --- v2/maker.go | 5 +++++ v2/maker_test.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/v2/maker.go b/v2/maker.go index 2b1276e..81866db 100644 --- a/v2/maker.go +++ b/v2/maker.go @@ -46,6 +46,11 @@ var makers = map[string]MakeCheckFunc{ nameURLUnescape: makeURLUnescape, } +// RegisterMaker registers a new maker function with the given name. +func RegisterMaker(name string, maker MakeCheckFunc) { + makers[name] = maker +} + // makeChecks take a checker config and returns the check functions. func makeChecks(config string) []CheckFunc[reflect.Value] { fields := strings.Fields(config) diff --git a/v2/maker_test.go b/v2/maker_test.go index 931183c..428bd3b 100644 --- a/v2/maker_test.go +++ b/v2/maker_test.go @@ -6,6 +6,8 @@ package v2_test import ( + "fmt" + "reflect" "testing" v2 "github.com/cinar/checker/v2" @@ -24,3 +26,51 @@ func TestMakeCheckersUnknown(t *testing.T) { v2.CheckStruct(person) } + +func ExampleRegisterMaker() { + v2.RegisterMaker("is-fruit", func(params string) v2.CheckFunc[reflect.Value] { + return func(value reflect.Value) (reflect.Value, error) { + stringValue := value.Interface().(string) + + if stringValue == "apple" || stringValue == "banana" { + return value, nil + } + + return value, v2.NewCheckError("NOT_FRUIT") + } + }) + + type Item struct { + Name string `checkers:"is-fruit"` + } + + person := &Item{ + Name: "banana", + } + + err, ok := v2.CheckStruct(person) + if !ok { + fmt.Println(err) + } +} + +func TestRegisterMaker(t *testing.T) { + v2.RegisterMaker("unknown", func(params string) v2.CheckFunc[reflect.Value] { + return func(value reflect.Value) (reflect.Value, error) { + return value, nil + } + }) + + type Person struct { + Name string `checkers:"unknown"` + } + + person := &Person{ + Name: "Onur", + } + + _, ok := v2.CheckStruct(person) + if !ok { + t.Fatal("expected valid") + } +}