这是indexloc提供的服务,不要输入任何密码
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -658,6 +658,8 @@ type SchemaTransformer interface {
// schema := huma.SchemaFromType(registry, reflect.TypeOf(MyType{}))
func SchemaFromType(r Registry, t reflect.Type) *Schema {
s := schemaFromType(r, t)
t = deref(t)

// Transform generated schema if type implements SchemaTransformer
v := reflect.New(t).Interface()
if st, ok := v.(SchemaTransformer); ok {
Expand Down
34 changes: 29 additions & 5 deletions schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,17 @@ func (t *TypedArrayWithCustomDesc) TransformSchema(r huma.Registry, s *huma.Sche
return s
}

var _ huma.SchemaTransformer = (*CustomSchemaPtr)(nil)

type CustomSchemaPtr struct {
Value string `json:"value"`
}

func (c *CustomSchemaPtr) TransformSchema(r huma.Registry, s *huma.Schema) *huma.Schema {
s.Description = "custom description"
return s
}

type TypedStringWithCustomLength string

func (c TypedStringWithCustomLength) Schema(r huma.Registry) *huma.Schema {
Expand Down Expand Up @@ -1005,7 +1016,9 @@ func TestSchema(t *testing.T) {
"properties":{
"value":{
"format":"int64",
"type": ["integer", "null"]
"type": ["integer", "null"],
"minimum":1,
"maximum":10
}
},
"required":["value"],
Expand Down Expand Up @@ -1058,6 +1071,21 @@ func TestSchema(t *testing.T) {
"type":"object"
}`,
},
{
name: "schema-transformer-for-ptr",
input: &CustomSchemaPtr{},
expected: ` {
"additionalProperties":false,
"description":"custom description",
"properties":{
"value":{
"type":"string"
}
},
"required":["value"],
"type":"object"
}`,
},
}

for _, c := range cases {
Expand Down Expand Up @@ -1098,7 +1126,6 @@ func TestSchemaOld(t *testing.T) {
r := huma.NewMapRegistry("#/components/schemas/", huma.DefaultSchemaNamer)

s := r.Schema(reflect.TypeOf(GreetingInput{}), false, "")
// fmt.Printf("%+v\n", s)
assert.Equal(t, "object", s.Type)
assert.Len(t, s.Properties, 1)
assert.Equal(t, "string", s.Properties["ID"].Type)
Expand All @@ -1115,9 +1142,6 @@ func TestSchemaOld(t *testing.T) {
},
}, &res)
assert.Empty(t, res.Errors)

// b, _ := json.MarshalIndent(r.Map(), "", " ")
// fmt.Println(string(b))
}

func TestSchemaGenericNaming(t *testing.T) {
Expand Down