Earlier swaggest URL parameter validation possible? #137
Unanswered
pboguslawski
asked this question in
Q&A
Replies: 1 comment
-
Validation is tightly tied to request decoding, and decoding is dependent on request structure that is represented by usecase input port. It is technically possible to run validation outside If (as per chi example) you need a shared piece of code that acts on a family of inputs, you can achieve that with usecase middleware. Please check the following example. package main
import (
"context"
"log"
"net/http"
"github.com/swaggest/rest/nethttp"
"github.com/swaggest/rest/web"
swgui "github.com/swaggest/swgui/v4emb"
"github.com/swaggest/usecase"
"github.com/swaggest/usecase/status"
)
type SomethingExposer interface {
Something() int
}
type someIn1 struct {
Foo int `query:"foo" minimum:"10"`
}
func (s someIn1) Something() int {
return s.Foo
}
type someIn2 struct {
Bar int `path:"bar" maximum:"20"`
}
func (s someIn2) Something() int {
return s.Bar
}
func somethingMW(magicNumber int) func(next http.Handler) http.Handler {
return nethttp.UseCaseMiddlewares(usecase.MiddlewareFunc(func(next usecase.Interactor) usecase.Interactor {
return usecase.Interact(func(ctx context.Context, input, output interface{}) error {
if se, ok := input.(SomethingExposer); ok {
if se.Something() == magicNumber { // Fail on specific condition.
return status.DataLoss
}
// Pass additional info via context (type safety can be improved with input interfaces instead of ctx).
return next.Interact(context.WithValue(ctx, "extra", 10*se.Something()), input, output)
}
return next.Interact(ctx, input, output)
})
}))
}
func main() {
s := web.DefaultService()
s.Wrap(somethingMW(15))
// Add use case handler to router.
s.Get("/one", usecase.NewInteractor(func(ctx context.Context, input someIn1, output *int) error {
*output = input.Foo
if extra, ok := ctx.Value("extra").(int); ok {
*output += extra
}
return nil
}))
s.Get("/two/{bar}", usecase.NewInteractor(func(ctx context.Context, input someIn2, output *int) error {
*output = input.Bar
if extra, ok := ctx.Value("extra").(int); ok {
*output += extra
}
return nil
}))
// Swagger UI endpoint at /docs.
s.Docs("/docs", swgui.New)
// Start server.
log.Println("http://localhost:8011/docs")
if err := http.ListenAndServe("localhost:8011", s); err != nil {
log.Fatal(err)
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Swaggest validates input params when interactor is called.
Is it possible to have URL parameters (from path and/or query) validated by swaggest earlier, to have parameter validated before execution of given middleware that loads resource on the context is called?
Beta Was this translation helpful? Give feedback.
All reactions