Skip to content

Commit

Permalink
Merge pull request #195 from danielgtaylor/generic-module-namer
Browse files Browse the repository at this point in the history
fix: schema naming for generics + package types
  • Loading branch information
danielgtaylor authored Jan 3, 2024
2 parents 7d204a1 + 79ec95d commit 57554dc
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
11 changes: 11 additions & 0 deletions registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,14 @@ 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 @@ -30,6 +35,12 @@ 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, "]", "")

Expand Down
14 changes: 14 additions & 0 deletions schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,20 @@ func TestSchemaGenericNaming(t *testing.T) {
}`, string(b))
}

func TestSchemaGenericNamingFromModule(t *testing.T) {
type SchemaGeneric[T any] struct {
Value T `json:"value"`
}

r := huma.NewMapRegistry("#/components/schemas/", huma.DefaultSchemaNamer)
s := r.Schema(reflect.TypeOf(SchemaGeneric[time.Time]{}), true, "")

b, _ := json.Marshal(s)
assert.JSONEq(t, `{
"$ref": "#/components/schemas/SchemaGenericTime"
}`, string(b))
}

type OmittableNullable[T any] struct { //nolint: musttag
Sent bool
Null bool
Expand Down

0 comments on commit 57554dc

Please sign in to comment.