Skip to content
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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# @digitalbazaar/http-client ChangeLog

## 1.2.0 - 2021-07-xx

### Added
- Ensure that body parsing will occur for JSON content types
when individual method functions (e.g., `get`, `post`) are
not used (e.g., `httpClient(url, {method: 'get'}`). Body
parsing can be disabled by passing the `parseBody` option
set to `false`.

## 1.1.0 - 2021-04-06

### Changed
Expand Down
32 changes: 20 additions & 12 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const proxyMethods = new Set([
]);

export const httpClient = new Proxy(ky, {
apply: _handleResponse,
get(target, propKey) {
const propValue = target[propKey];

Expand All @@ -22,22 +23,29 @@ export const httpClient = new Proxy(ky, {
return propValue;
}
return async function() {
let response;
try {
response = await propValue.apply(this, arguments);
} catch(e) {
return _handleError(e);
}
// a 204 will not include a content-type header
const contentType = response.headers.get('content-type');
if(contentType && contentType.includes('json')) {
response.data = await response.json();
}
return response;
return _handleResponse(propValue, this, arguments);
};
}
});

async function _handleResponse(target, thisArg, args) {
let response;
try {
response = await target.apply(thisArg, args);
} catch(e) {
return _handleError(e);
}
const {parseBody = true} = args[1] || {};
if(parseBody) {
// a 204 will not include a content-type header
const contentType = response.headers.get('content-type');
if(contentType && contentType.includes('json')) {
response.data = await response.json();
}
}
return response;
}

async function _handleError(e) {
// handle network errors that do not have a response
if(!e.response) {
Expand Down