Skip to content

Commit

Permalink
chore: add HandlerFnOfOK to provide canonical request body validation
Browse files Browse the repository at this point in the history
  • Loading branch information
jsteenb2 committed Aug 5, 2024
1 parent 735a63e commit 5d2d10f
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
12 changes: 12 additions & 0 deletions sdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,18 @@ func HandleFnOf[T any](fn func(context.Context, RequestOf[T]) Response) Handler
})
}

// HandlerFnOfOK provides a means to translate the incoming requests to the destination body type
// and execute validation on that type. This normalizes the sad path for both the unmarshalling of
// the request body and the validation of that request type using its OK() method.
func HandlerFnOfOK[T interface{ OK() []APIError }](fn func(context.Context, RequestOf[T]) Response) Handler {
return HandleFnOf(func(ctx context.Context, r RequestOf[T]) Response {
if errs := r.Body.OK(); len(errs) > 0 {
return ErrResp(errs...)
}
return fn(ctx, r)
})
}

// WorkflowCtx is the Request.Context field when integrating a function with Falcon Fusion workflow.
type WorkflowCtx struct {
ActivityExecID string `json:"activity_execution_id"`
Expand Down
45 changes: 45 additions & 0 deletions sdk_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package fdk_test

import (
"context"
"encoding/json"
"fmt"
"net/http"
"testing"
Expand All @@ -19,3 +21,46 @@ func TestAPIError(t *testing.T) {
fdk.EqualVals(t, want, err.Error())
}
}

func TestHandlerFnOfOK(t *testing.T) {
h := fdk.HandlerFnOfOK(func(ctx context.Context, r fdk.RequestOf[okReq]) fdk.Response {
return fdk.Response{Code: http.StatusOK}
})

b, err := json.Marshal(okReq{
Shoulds: []int{
http.StatusOK, // should not cause an error
http.StatusBadRequest, // should return a 400 error
http.StatusInternalServerError, // should return a 500 error
},
})
mustNoErr(t, err)

resp := h.Handle(context.TODO(), fdk.Request{Body: b})
fdk.EqualVals(t, http.StatusInternalServerError, resp.Code)

wantErrs := []fdk.APIError{
{Code: http.StatusBadRequest, Message: http.StatusText(http.StatusBadRequest)},
{Code: http.StatusInternalServerError, Message: http.StatusText(http.StatusInternalServerError)},
}
if !fdk.EqualVals(t, len(wantErrs), len(resp.Errors)) {
return
}
fdk.EqualVals(t, wantErrs[0], resp.Errors[0])
fdk.EqualVals(t, wantErrs[1], resp.Errors[1])
}

type okReq struct {
Shoulds []int `json:"shoulds"`
}

func (r okReq) OK() []fdk.APIError {
var out []fdk.APIError
for _, sh := range r.Shoulds {
if sh < 400 {
continue
}
out = append(out, fdk.APIError{Code: sh, Message: http.StatusText(sh)})
}
return out
}

0 comments on commit 5d2d10f

Please sign in to comment.