Skip to content

Commit

Permalink
Remove deprecated params and add option to replace error if already set
Browse files Browse the repository at this point in the history
  • Loading branch information
EwenQuim committed Dec 6, 2024
1 parent a4ad38e commit 5b9f9b3
Show file tree
Hide file tree
Showing 6 changed files with 38 additions and 27 deletions.
4 changes: 2 additions & 2 deletions mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import (
// return ans{Ans: "users"}, nil
// })
// s.Run()
func Group(s *Server, path string, options ...func(*BaseRoute)) *Server {
func Group(s *Server, path string, routeOptions ...func(*BaseRoute)) *Server {
if path == "/" {
path = ""
} else if path != "" && path[len(path)-1] == '/' {
Expand All @@ -44,7 +44,7 @@ func Group(s *Server, path string, options ...func(*BaseRoute)) *Server {
Params: make(map[string]OpenAPIParam),
Operation: openapi3.NewOperation(),
}
for _, option := range options {
for _, option := range routeOptions {
option(&baseRoute)
}

Expand Down
2 changes: 1 addition & 1 deletion openapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ func RegisterOpenAPIOperation[T, B any](s *Server, route Route[T, B]) (*openapi3

// Response - globals
for _, openAPIGlobalResponse := range s.globalOpenAPIResponses {
addResponse(s, route.Operation, openAPIGlobalResponse.Code, openAPIGlobalResponse.Description, openAPIGlobalResponse.ErrorType)
addResponseIfNotSet(s, route.Operation, openAPIGlobalResponse.Code, openAPIGlobalResponse.Description, openAPIGlobalResponse.ErrorType)
}

// Automatically add non-declared 200 Response
Expand Down
23 changes: 10 additions & 13 deletions openapi_operations.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package fuego

import (
"strconv"

"github.com/getkin/kin-openapi/openapi3"
)

Expand Down Expand Up @@ -52,15 +54,8 @@ func (r Route[ResponseBody, RequestBody]) Param(paramType ParamType, name, descr
return r
}

// AddError adds an error to the route.
//
// Deprecated: Use `option.AddError` from github.com/go-fuego/fuego/option instead.
func (r Route[ResponseBody, RequestBody]) AddError(code int, description string, errorType ...any) Route[ResponseBody, RequestBody] {
addResponse(r.mainRouter, r.Operation, code, description, errorType...)
return r
}

func addResponse(s *Server, operation *openapi3.Operation, code int, description string, errorType ...any) {
// Registers a response for the route, only if error for this code is not already set.
func addResponseIfNotSet(s *Server, operation *openapi3.Operation, code int, description string, errorType ...any) {
var responseSchema SchemaTag

if len(errorType) > 0 {
Expand All @@ -70,11 +65,13 @@ func addResponse(s *Server, operation *openapi3.Operation, code int, description
}
content := openapi3.NewContentWithSchemaRef(&responseSchema.SchemaRef, []string{"application/json"})

response := openapi3.NewResponse().
WithDescription(description).
WithContent(content)
if operation.Responses.Value(strconv.Itoa(code)) == nil {
response := openapi3.NewResponse().
WithDescription(description).
WithContent(content)

operation.AddResponse(code, response)
operation.AddResponse(code, response)
}
}

// openAPIError describes a response error in the OpenAPI spec.
Expand Down
16 changes: 9 additions & 7 deletions openapi_operations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,9 @@ func TestCustomError(t *testing.T) {
Message string
}
s := NewServer()
route := Get(s, "/test", testController).
AddError(400, "My Validation Error", MyError{})
route := Get(s, "/test", testController,
OptionAddError(400, "My Validation Error", MyError{}),
)

require.Equal(t, "My Validation Error", *route.Operation.Responses.Map()["400"].Value.Description)
}
Expand All @@ -74,12 +75,13 @@ func TestCustomErrorGlobalAndOnRoute(t *testing.T) {
}

routeGlobal := Get(s, "/test-global", testController)
routeCustom := Get(s, "/test-custom", testController).
AddError(400, "My Local Error", MyLocalError{}).
AddError(419, "My Local Teapot")
routeCustom := Get(s, "/test-custom", testController,
OptionAddError(400, "My Local Error", MyLocalError{}),
OptionAddError(419, "My Local Teapot"),
)

require.Equal(t, "My Global Error", *routeGlobal.Operation.Responses.Map()["400"].Value.Description, "Overrides Fuego's default 400 error")
require.Equal(t, "Another Global Error", *routeGlobal.Operation.Responses.Map()["501"].Value.Description)
require.Equal(t, "My Global Error", *routeGlobal.Operation.Responses.Value("400").Value.Description, "Overrides Fuego's default 400 error")
require.Equal(t, "Another Global Error", *routeGlobal.Operation.Responses.Value("501").Value.Description)

require.Equal(t, "My Local Error", *routeCustom.Operation.Responses.Map()["400"].Value.Description, "Local error overrides global error")
require.Equal(t, "My Local Teapot", *routeCustom.Operation.Responses.Map()["419"].Value.Description)
Expand Down
8 changes: 7 additions & 1 deletion option.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package fuego
import (
"fmt"
"net/http"
"strconv"

"github.com/getkin/kin-openapi/openapi3"
)
Expand Down Expand Up @@ -231,6 +232,7 @@ func OptionDeprecated() func(*BaseRoute) {
}

// AddError adds an error to the route.
// It replaces any existing error previously set with the same code.
// Required: should only supply one type to `errorType`
func OptionAddError(code int, description string, errorType ...any) func(*BaseRoute) {
var responseSchema SchemaTag
Expand All @@ -249,7 +251,11 @@ func OptionAddError(code int, description string, errorType ...any) func(*BaseRo
response := openapi3.NewResponse().
WithDescription(description).
WithContent(content)
r.Operation.AddResponse(code, response)

if r.Operation.Responses == nil {
r.Operation.Responses = openapi3.NewResponses()
}
r.Operation.Responses.Set(strconv.Itoa(code), &openapi3.ResponseRef{Value: response})
}
}

Expand Down
12 changes: 9 additions & 3 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,17 +124,23 @@ func NewServer(options ...func(*Server)) *Server {
Security: NewSecurity(),
}

// Default options that can be overridden
defaultOptions := [...]func(*Server){
WithAddr("localhost:9999"),
WithDisallowUnknownFields(true),
WithSerializer(Send),
WithErrorSerializer(SendError),
WithErrorHandler(ErrorHandler),
}
options = append(defaultOptions[:], options...)

// Options set if not provided
options = append(options,
WithGlobalResponseTypes(http.StatusBadRequest, "Bad Request _(validation or deserialization error)_", HTTPError{}),
WithGlobalResponseTypes(http.StatusInternalServerError, "Internal Server Error _(panics)_", HTTPError{}),
}
)

for _, option := range append(defaultOptions[:], options...) {
for _, option := range options {
option(s)
}

Expand Down Expand Up @@ -203,7 +209,7 @@ func WithCorsMiddleware(corsMiddleware func(http.Handler) http.Handler) func(*Se
}

// WithGlobalResponseTypes adds default response types to the server.
// useful for adding global error types.
// Useful for adding global error types.
// For example:
//
// app := fuego.NewServer(
Expand Down

0 comments on commit 5b9f9b3

Please sign in to comment.