diff --git a/openapi/builder.go b/openapi/builder.go index 27ad910..efe3f61 100644 --- a/openapi/builder.go +++ b/openapi/builder.go @@ -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 @@ -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 } @@ -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 +} diff --git a/utils/path_formatting.go b/utils/path_formatting.go new file mode 100644 index 0000000..73e382c --- /dev/null +++ b/utils/path_formatting.go @@ -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 +}