Skip to content

Commit

Permalink
Merge pull request #532 from fourcels/fix-schema-example
Browse files Browse the repository at this point in the history
fix(schema): schema example not work in Parameter
  • Loading branch information
danielgtaylor authored Aug 5, 2024
2 parents a3e556b + 40d5603 commit 9975252
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
3 changes: 3 additions & 0 deletions huma.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,9 @@ func findParams(registry Registry, op *Operation, t reflect.Type) *findResult[*p
if e := f.Tag.Get("example"); e != "" {
example = jsonTagValue(registry, f.Type.Name(), pfi.Schema, f.Tag.Get("example"))
}
if example == nil && len(pfi.Schema.Examples) > 0 {
example = pfi.Schema.Examples[0]
}

// While discouraged, make it possible to make query/header params required.
if r := f.Tag.Get("required"); r == "true" {
Expand Down
26 changes: 26 additions & 0 deletions huma_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2134,6 +2134,32 @@ func TestUnsupportedEmbeddedTypeWithMethods(t *testing.T) {
})
}

type SchemaWithExample int

func (*SchemaWithExample) Schema(r huma.Registry) *huma.Schema {
schema := &huma.Schema{
Type: huma.TypeInteger,
Examples: []any{1},
}
return schema
}

func TestSchemaWithExample(t *testing.T) {
_, app := humatest.New(t, huma.DefaultConfig("Test API", "1.0.0"))
huma.Register(app, huma.Operation{
OperationID: "test",
Method: http.MethodGet,
Path: "/test",
}, func(ctx context.Context, input *struct {
Test SchemaWithExample `query:"test"`
}) (*struct{}, error) {
return nil, nil
})

example := app.OpenAPI().Paths["/test"].Get.Parameters[0].Example
assert.Equal(t, 1, example)
}

// func BenchmarkSecondDecode(b *testing.B) {
// //nolint: musttag
// type MediumSized struct {
Expand Down

0 comments on commit 9975252

Please sign in to comment.