Skip to content

Commit

Permalink
Transform and Validate Gin input
Browse files Browse the repository at this point in the history
  • Loading branch information
EwenQuim committed Dec 25, 2024
1 parent 7dd8125 commit eda8d39
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 35 deletions.
53 changes: 20 additions & 33 deletions deserialization.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,21 +104,7 @@ func read[B any](context context.Context, dec decoder) (B, error) {
}
slog.Debug("Decoded body", "body", body)

body, err = transform(context, body)
if err != nil {
return body, BadRequestError{
Title: "Transformation Failed",
Err: err,
Detail: "cannot transform request body: " + err.Error(),
}
}

err = validate(body)
if err != nil {
return body, err
}

return body, nil
return TransformAndValidate(context, body)
}

// ReadString reads the request body as string.
Expand Down Expand Up @@ -199,24 +185,7 @@ func readURLEncoded[B any](r *http.Request, options readOptions) (B, error) {
}
slog.Debug("Decoded body", "body", body)

body, err = transform(r.Context(), body)
if err != nil {
return body, BadRequestError{
Title: "Transformation Failed",
Detail: "cannot transform x-www-form-urlencoded request body: " + err.Error(),
Err: err,
Errors: []ErrorItem{
{Name: "transformation", Reason: "transformation failed"},
},
}
}

err = validate(body)
if err != nil {
return body, fmt.Errorf("cannot validate request body: %w", err)
}

return body, nil
return TransformAndValidate(r.Context(), body)
}

// transforms the input if possible.
Expand All @@ -225,8 +194,12 @@ func transform[B any](ctx context.Context, body B) (B, error) {
err := inTransformerBody.InTransform(ctx)
if err != nil {
return body, BadRequestError{
Title: "Transformation Failed",
Err: err,
Detail: "cannot transform request body: " + err.Error(),
Errors: []ErrorItem{
{Name: "transformation", Reason: "transformation failed"},
},
}
}
body = *any(inTransformerBody).(*B)
Expand All @@ -236,3 +209,17 @@ func transform[B any](ctx context.Context, body B) (B, error) {

return body, nil
}

func TransformAndValidate[B any](context context.Context, body B) (B, error) {
body, err := transform(context, body)
if err != nil {
return body, err
}

err = validate(body)
if err != nil {
return body, err
}

return body, nil
}
7 changes: 5 additions & 2 deletions extra/fuegogin/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,11 @@ var (

func (c ginContext[B]) Body() (B, error) {
var body B
err := c.ginCtx.BindJSON(&body)
return body, err
err := c.ginCtx.Bind(&body)
if err != nil {
return body, err
}
return fuego.TransformAndValidate(c, body)
}

func (c ginContext[B]) Context() context.Context {
Expand Down

0 comments on commit eda8d39

Please sign in to comment.