Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: more robust nil check for link transformer #418

Merged
merged 1 commit into from
Apr 28, 2024
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
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
Loading