Skip to content

Commit

Permalink
Register maker is added. (#149)
Browse files Browse the repository at this point in the history
# Describe Request

Register maker is added.

# Change Type

New code.
  • Loading branch information
cinar authored Dec 27, 2024
1 parent 23f3064 commit b9d2edb
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
5 changes: 5 additions & 0 deletions v2/maker.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
50 changes: 50 additions & 0 deletions v2/maker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
package v2_test

import (
"fmt"
"reflect"
"testing"

v2 "github.com/cinar/checker/v2"
Expand All @@ -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")
}
}

0 comments on commit b9d2edb

Please sign in to comment.