Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add option for custom validator #65

Merged
merged 1 commit into from
Mar 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"time"

"github.com/getkin/kin-openapi/openapi3"
"github.com/go-playground/validator/v10"
"github.com/golang-jwt/jwt/v5"
)

Expand Down Expand Up @@ -261,3 +262,25 @@ func WithOpenapiConfig(openapiConfig OpenapiConfig) func(*Server) {
}
}
}

// WithValidator sets the validator to be used by the fuego server.
// If no validator is provided, a default validator will be used.
//
// Note: If you are using the default validator, you can add tags to your structs using the `validate` tag.
// For example:
//
// type MyStruct struct {
// Field1 string `validate:"required"`
// Field2 int `validate:"min=10,max=20"`
// }
//
// The above struct will be validated using the default validator, and if any errors occur, they will be returned as part of the response.
func WithValidator(newValidator *validator.Validate) func(*Server) {
if newValidator == nil {
panic("new validator not provided")
}

return func(s *Server) {
v = newValidator
}
}
43 changes: 43 additions & 0 deletions options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"net/http/httptest"
"testing"

"github.com/go-playground/validator/v10"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -179,3 +181,44 @@ func TestWithLogHandler(t *testing.T) {
WithLogHandler(handler),
)
}

func TestWithValidator(t *testing.T) {
type args struct {
newValidator *validator.Validate
}
tests := []struct {
name string
args args
wantPanic bool
}{
{
name: "with custom validator",
args: args{
newValidator: validator.New(),
},
},
{
name: "no validator provided",
args: args{
newValidator: nil,
},
wantPanic: true,
},
}
for _, tt := range tests {
t.Run(
tt.name, func(t *testing.T) {
if tt.wantPanic {
assert.Panics(
t, func() { WithValidator(tt.args.newValidator) },
)
} else {
NewServer(
WithValidator(tt.args.newValidator),
)
assert.Equal(t, tt.args.newValidator, v)
}
},
)
}
}
Loading