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: correctly handle empty response bodies #239

Merged
merged 1 commit into from
Mar 1, 2023
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
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