Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
PR danielgtaylor#195 fixed ISSUE danielgtaylor#198. But regex matched a shorter string when a generic parammeter is an slice( that means there's embedded brackets).
  • Loading branch information
qdongxu committed Jan 4, 2024
1 parent 4b5f0d1 commit c55a279
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 13 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ mem.out
docs/site
docs/__pycache__
docs/.cache
.idea/
21 changes: 8 additions & 13 deletions registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,9 @@ import (
"encoding/json"
"fmt"
"reflect"
"regexp"
"strings"
)

// reGenericName helps to convert `MyType[path/to.SubType]` to `MyTypeSubType`
// when using the default schema namer.
var reGenericName = regexp.MustCompile(`\[[^\]]+\]`)

// Registry creates and stores schemas and their references, and supports
// marshalling to JSON/YAML for use as an OpenAPI #/components/schemas object.
// Behavior is implementation-dependent, but the design allows for recursive
Expand All @@ -35,14 +30,14 @@ func DefaultSchemaNamer(t reflect.Type, hint string) string {
name := deref(t).Name()

// Fix up generics, if used, for nicer refs & URLs.
name = reGenericName.ReplaceAllStringFunc(name, func(s string) string {
// Convert `MyType[path/to.SubType]` to `MyType[SubType]`.
parts := strings.Split(s, ".")
return parts[len(parts)-1]
})
// Remove square brackets.
name = strings.ReplaceAll(name, "[", "")
name = strings.ReplaceAll(name, "]", "")
// Convert `MyType[path/to.SubType]` to `MyTypepathtoSubType`.
replaced := strings.Builder{}
for _, c := range name {
if !strings.ContainsRune("[*/.]", c) {
replaced.WriteRune(c)
}
}
name = replaced.String()

if name == "" {
name = hint
Expand Down
27 changes: 27 additions & 0 deletions registry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package huma

import (
"fmt"
"reflect"
"testing"

"github.com/danielgtaylor/huma/v2/examples/protodemo/protodemo"
"github.com/stretchr/testify/assert"
)

type Output[T any] struct {
data T
}

type Embedded[P any] struct {
data P
}

func TestDefaultSchemaNamer(t *testing.T) {
testUser := Output[*[]Embedded[protodemo.User]]{}

name := DefaultSchemaNamer(reflect.TypeOf(testUser), "hint")
fmt.Println(reflect.TypeOf(testUser))
fmt.Println(name)
assert.True(t, name == "Outputgithubcomdanielgtaylorhumav2Embeddedgithubcomdanielgtaylorhumav2examplesprotodemoprotodemoUser")
}

0 comments on commit c55a279

Please sign in to comment.