-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Make responseHandlers as a helper & wrap response.
- Loading branch information
1 parent
52f29e5
commit 3b19a69
Showing
4 changed files
with
135 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
/** | ||
* Wrapp a response | ||
* | ||
* @param {Object} response response object | ||
* @param {String} reader type of reader to use on response body | ||
* @return {Promise} resolves to the wrapped read response | ||
*/ | ||
function wrapResponse(response, reader) { | ||
return response[reader]() | ||
.then(data => ({ | ||
headers: response.headers, | ||
status: response.status, | ||
data | ||
})); | ||
} | ||
|
||
/** | ||
* Reads or rejects a fetch request response | ||
* | ||
* @param {Object} response response object | ||
* @return {Promise} read or rejection promise | ||
*/ | ||
function responseHandler(response) { | ||
if (!response.ok) { | ||
const err = new Error(response.statusText); | ||
err.status = response.status; | ||
err.headers = response.headers; | ||
return Promise.reject(err); | ||
} | ||
if (response.headers.get('Content-Type') === 'application/json') { | ||
return wrapResponse(response, 'json'); | ||
} | ||
return wrapResponse(response, 'text'); | ||
} | ||
|
||
module.exports = responseHandler; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters