diff --git a/CHANGELOG.md b/CHANGELOG.md index 629d579..802e57f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/main.js b/main.js index c4976e2..64209b4 100644 --- a/main.js +++ b/main.js @@ -14,6 +14,7 @@ const proxyMethods = new Set([ ]); export const httpClient = new Proxy(ky, { + apply: _handleResponse, get(target, propKey) { const propValue = target[propKey]; @@ -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) {