Skip to content

Commit

Permalink
fix: more robust nil check for link transformer
Browse files Browse the repository at this point in the history
  • Loading branch information
danielgtaylor committed Apr 28, 2024
1 parent babafa8 commit 7f74b7d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
24 changes: 24 additions & 0 deletions huma_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1114,6 +1114,30 @@ Content of example2.txt.
assert.Equal(t, `hello`, resp.Body.String())
},
},
{
Name: "response-transform-nil-body",
Transformers: []huma.Transformer{
huma.NewSchemaLinkTransformer("/", "/").Transform,
},
Register: func(t *testing.T, api huma.API) {
huma.Get(api, "/transform", func(ctx context.Context, i *struct{}) (*struct {
Body *struct {
Field string `json:"field"`
}
}, error) {
return &struct {
Body *struct {
Field string `json:"field"`
}
}{}, nil
})
},
Method: http.MethodGet,
URL: "/transform",
Assert: func(t *testing.T, resp *httptest.ResponseRecorder) {
assert.Equal(t, http.StatusOK, resp.Code)
},
},
{
Name: "response-transform-error",
Transformers: []huma.Transformer{
Expand Down
5 changes: 3 additions & 2 deletions transforms.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,8 @@ func (t *SchemaLinkTransformer) OnAddOperation(oapi *OpenAPI, op *Operation) {
// Transform is called for every response to add the `$schema` field and/or
// the Link header pointing to the JSON Schema.
func (t *SchemaLinkTransformer) Transform(ctx Context, status string, v any) (any, error) {
if v == nil {
vv := reflect.ValueOf(v)
if vv.Kind() == reflect.Pointer && vv.IsNil() {
return v, nil
}

Expand Down Expand Up @@ -184,7 +185,7 @@ func (t *SchemaLinkTransformer) Transform(ctx Context, status string, v any) (an
bufPool.Put(buf)

// Copy over all the exported fields.
vv := reflect.Indirect(reflect.ValueOf(v))
vv = reflect.Indirect(vv)
for i, j := range info.fields {
// Field 0 is the $schema field, so we need to offset the index by one.
// There might have been unexported fields in the struct declared in the schema,
Expand Down

0 comments on commit 7f74b7d

Please sign in to comment.