Skip to content

Commit

Permalink
fix: correctly handle empty response bodies (#239)
Browse files Browse the repository at this point in the history
There are cases, such as a HEAD request, where the response body will have
a JSON content type but the body will be empty (i.e. an empty string). This
is technically valid JSON but is not parsable into an object, so the code
throws an exception. This commit adds specific handling for this scenario,
as well as a couple of test cases

Signed-off-by: Dustin Popp <[email protected]>
  • Loading branch information
dpopp07 authored Mar 1, 2023
1 parent b599735 commit d0c9cb3
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/request-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -557,7 +557,13 @@ function parseServiceErrorMessage(response: any): string | undefined {
* @throws error - if the content is meant as JSON but is malformed
*/
function ensureJSONResponseBodyIsObject(response: any): any | string {
if (typeof response.data !== 'string' || !isJsonMimeType(response.headers['content-type'])) {
// If axios gave us an empty string, it is because the response had an empty body
// which can happen for a HEAD request, etc. Return the empty string in that case
if (
typeof response.data !== 'string' ||
response.data === '' ||
!isJsonMimeType(response.headers['content-type'])
) {
return response.data;
}

Expand Down
42 changes: 42 additions & 0 deletions test/unit/request-wrapper.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -646,6 +646,48 @@ describe('sendRequest', () => {
expect(res.result).toEqual({ key: 'value' });
});

it('should return empty string when body is empty and content is JSON', async () => {
const parameters = {
defaultOptions: {
body: 'post=body',
formData: '',
qs: {},
method: 'POST',
url: 'https://example.ibm.com/v1/environments',
headers: {},
responseType: 'json',
},
};

axiosResolveValue.data = '';
axiosResolveValue.headers = { 'content-type': 'application/json' };
mockAxiosInstance.mockResolvedValue(axiosResolveValue);

const res = await requestWrapperInstance.sendRequest(parameters);
expect(res.result).toBe('');
});

it('should return null when body is null and content is JSON', async () => {
const parameters = {
defaultOptions: {
body: 'post=body',
formData: '',
qs: {},
method: 'POST',
url: 'https://example.ibm.com/v1/environments',
headers: {},
responseType: 'json',
},
};

axiosResolveValue.data = null;
axiosResolveValue.headers = { 'content-type': 'application/json' };
mockAxiosInstance.mockResolvedValue(axiosResolveValue);

const res = await requestWrapperInstance.sendRequest(parameters);
expect(res.result).toBeNull();
});

it('should raise exception when response body content is invalid json', async () => {
const parameters = {
defaultOptions: {
Expand Down

0 comments on commit d0c9cb3

Please sign in to comment.