Skip to content

Commit 79b3b80

Browse files
authored
Merge pull request #65 from calvinmclean/feature/improve-generic-request
Improve MakeGenericRequest to return response
2 parents 25f31ca + 29d658e commit 79b3b80

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

babyapi_test.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -1425,9 +1425,11 @@ func TestGetAllResponseWrapperWithClient(t *testing.T) {
14251425
require.NoError(t, err)
14261426

14271427
var albums AllAlbumsWrapper
1428-
err = client.MakeGenericRequest(req, &albums)
1428+
resp, err := client.MakeGenericRequest(req, &albums)
14291429
require.NoError(t, err)
14301430
require.Equal(t, "Album", albums[0].Title)
1431+
require.NotNil(t, resp.Data)
1432+
require.Equal(t, http.StatusOK, resp.Response.StatusCode)
14311433
})
14321434

14331435
t.Run("GetAllCLI", func(t *testing.T) {

client.go

+12-6
Original file line numberDiff line numberDiff line change
@@ -401,27 +401,33 @@ func (c *Client[T]) MakeRequest(req *http.Request, expectedStatusCode int) (*Res
401401

402402
// MakeGenericRequest allows making a request without specifying the return type. It accepts a pointer receiver
403403
// to pass to json.Unmarshal. This allows returning any type using the Client.
404-
func (c *Client[T]) MakeGenericRequest(req *http.Request, target any) error {
404+
func (c *Client[T]) MakeGenericRequest(req *http.Request, target any) (*Response[any], error) {
405405
resp, err := makeRequest(req, c.client, c.requestEditor)
406406
if err != nil {
407-
return err
407+
return nil, err
408+
}
409+
410+
result := &Response[any]{
411+
Response: resp,
412+
Data: target,
408413
}
409414

410415
if resp.Body == nil {
411-
return nil
416+
return result, nil
412417
}
413418

414419
body, err := io.ReadAll(resp.Body)
415420
if err != nil {
416-
return fmt.Errorf("error decoding error response: %w", err)
421+
return nil, fmt.Errorf("error decoding error response: %w", err)
417422
}
423+
result.Body = string(body)
418424

419425
err = json.Unmarshal(body, target)
420426
if err != nil {
421-
return fmt.Errorf("error decoding response body %q: %w", string(body), err)
427+
return nil, fmt.Errorf("error decoding response body %q: %w", string(body), err)
422428
}
423429

424-
return nil
430+
return result, nil
425431
}
426432

427433
// MakeRequest generically sends an HTTP request after calling the request editor and checks the response code

0 commit comments

Comments
 (0)