Skip to content

Commit

Permalink
Reduce cognitive complexity of router builder code
Browse files Browse the repository at this point in the history
  • Loading branch information
Icikowski committed Jul 9, 2022
1 parent e1e4269 commit ead3748
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 9 deletions.
14 changes: 5 additions & 9 deletions application/service/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,11 @@ func getHandlerForRoute(path string, route config.Route, log zerolog.Logger) fun
w.Header().Set(headerName, headerValue)
}
}
if status == nil {
status = utils.PointerTo(http.StatusOK)
}
if contentType == nil {
contentType = utils.PointerTo("text/plain")
}
if content == nil {
content = new(string)
}

status = utils.GetOptionalOrFallback(status, utils.PointerTo(http.StatusOK))
contentType = utils.GetOptionalOrFallback(contentType, utils.PointerTo("text/plain"))
content = utils.GetOptionalOrFallback(content, new(string))

if strings.HasPrefix(strings.TrimSpace(*content), "base64,") {
var err error
finalContent, err = base64.StdEncoding.DecodeString(strings.TrimPrefix(strings.TrimSpace(*content), "base64,"))
Expand Down
9 changes: 9 additions & 0 deletions application/utils/optional.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package utils

// GetOptionalOrFallback returns pointer to value if value is not empty or fallback pointer otherwise
func GetOptionalOrFallback[T any](value *T, fallback *T) *T {
if value == nil {
return fallback
}
return value
}
34 changes: 34 additions & 0 deletions application/utils/optional_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package utils

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestGetOptionalOrFallback(t *testing.T) {
someValue, someFallback := PointerTo("someValue"), PointerTo("someFallback")
tests := map[string]struct {
value *string
fallback *string
expectedValue *string
}{
"value is not nil": {
value: someValue,
fallback: someFallback,
expectedValue: someValue,
},
"value is nil": {
value: nil,
fallback: someFallback,
expectedValue: someFallback,
},
}

for name, tc := range tests {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.expectedValue, GetOptionalOrFallback(tc.value, tc.fallback))
})
}
}

0 comments on commit ead3748

Please sign in to comment.