Skip to content

Commit

Permalink
Merge pull request #19 from MWM-io/dr/add-with-operation-id
Browse files Browse the repository at this point in the history
[openapi] Add WithOperationID and set a default one when invoking WithSummary()
  • Loading branch information
Dmouri committed Nov 16, 2023
2 parents dfd23a7 + 228288f commit 912c9a0
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
9 changes: 9 additions & 0 deletions openapi/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/swaggest/openapi-go/openapi3"

"github.com/mwm-io/gapi/errors"
"github.com/mwm-io/gapi/utils"
)

// DocBuilder is a builder to simplify the documentation of an operation
Expand Down Expand Up @@ -64,6 +65,8 @@ func (b *DocBuilder) Error() error {
// WithSummary set a Summary (Title) to the operation
func (b *DocBuilder) WithSummary(summary string) *DocBuilder {
b.operation.WithSummary(summary)
defaultOperationID := utils.GenerateOperationID("/" + b.httpMethod + b.path)
b.operation.ID = &defaultOperationID
return b
}

Expand Down Expand Up @@ -239,3 +242,9 @@ func (b *DocBuilder) WithError(statusCode int, kind, message string, options ...

return b
}

// WithOperationID set an operationID to the operation
func (b *DocBuilder) WithOperationID(operationID string) *DocBuilder {
b.operation.ID = &operationID
return b
}
33 changes: 33 additions & 0 deletions utils/path_formatting.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package utils

import (
"regexp"
"strings"
)

func toTitleCase(s string) string {
if s == "" {
return s
}
return strings.ToUpper(s[:1]) + s[1:]
}

func GenerateOperationID(path string) string {
re := regexp.MustCompile(`{([^}]+)}`)
path = re.ReplaceAllString(path, "")

pathParts := strings.Split(path, "/")
for i, part := range pathParts {
if part != "" {
pathParts[i] = toTitleCase(strings.ToLower(part))
}
}
operationID := strings.Join(pathParts, "")

operationID = strings.ReplaceAll(operationID, "-", "")
operationID = strings.ReplaceAll(operationID, "/", "")
operationID = strings.ReplaceAll(operationID, "_", "")
operationID = strings.ToLower(operationID[:1]) + operationID[1:]

return operationID
}

0 comments on commit 912c9a0

Please sign in to comment.