Skip to content

Commit

Permalink
fix: body with ContentTypeFilter should update OpenAPI
Browse files Browse the repository at this point in the history
  • Loading branch information
danielgtaylor committed Dec 5, 2024
1 parent 0fefc6f commit ba685ef
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
12 changes: 9 additions & 3 deletions huma.go
Original file line number Diff line number Diff line change
Expand Up @@ -804,11 +804,17 @@ func Register[I, O any](api API, op Operation, handler func(context.Context, *I)
if op.Responses[statusStr].Content == nil {
op.Responses[statusStr].Content = map[string]*MediaType{}
}
// Check if the field's type implements ContentTypeFilter
contentType := "application/json"
if reflect.PointerTo(f.Type).Implements(reflect.TypeFor[ContentTypeFilter]()) {
instance := reflect.New(f.Type).Interface().(ContentTypeFilter)
contentType = instance.ContentType(contentType)
}
if len(op.Responses[statusStr].Content) == 0 {
op.Responses[statusStr].Content["application/json"] = &MediaType{}
op.Responses[statusStr].Content[contentType] = &MediaType{}
}
if op.Responses[statusStr].Content["application/json"] != nil && op.Responses[statusStr].Content["application/json"].Schema == nil {
op.Responses[statusStr].Content["application/json"].Schema = outSchema
if op.Responses[statusStr].Content[contentType] != nil && op.Responses[statusStr].Content[contentType].Schema == nil {
op.Responses[statusStr].Content[contentType].Schema = outSchema
}
}
}
Expand Down
25 changes: 25 additions & 0 deletions huma_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2005,6 +2005,31 @@ func TestOpenAPI(t *testing.T) {
})
}

type CTFilterBody struct {
Field string `json:"field"`
}

func (b *CTFilterBody) ContentType(ct string) string {
return "application/custom+json"
}

var _ huma.ContentTypeFilter = (*CTFilterBody)(nil)

func TestContentTypeFilter(t *testing.T) {
_, api := humatest.New(t, huma.DefaultConfig("Test API", "1.0.0"))
huma.Get(api, "/ct-filter", func(ctx context.Context, i *struct{}) (*struct {
Body CTFilterBody
}, error) {
return nil, nil
})

responses := api.OpenAPI().Paths["/ct-filter"].Get.Responses["200"].Content
assert.Equal(t, 1, len(responses))

Check failure on line 2027 in huma_test.go

View workflow job for this annotation

GitHub Actions / Build & Test (1.21)

len: use assert.Len (testifylint)

Check failure on line 2027 in huma_test.go

View workflow job for this annotation

GitHub Actions / Build & Test (1.22)

len: use assert.Len (testifylint)

Check failure on line 2027 in huma_test.go

View workflow job for this annotation

GitHub Actions / Build & Test (1.23)

len: use assert.Len (testifylint)
for k := range responses {
assert.Equal(t, "application/custom+json", k)
}
}

type IntNot3 int

func (i IntNot3) Resolve(ctx huma.Context, prefix *huma.PathBuffer) []error {
Expand Down

0 comments on commit ba685ef

Please sign in to comment.