diff --git a/CHANGELOG.md b/CHANGELOG.md index a62776e..fbc7c98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed * Remove Travis CI - [products/#97](https://github.com/ripe-tech/products/issues/97) +* Better verification of response errors and error message ### Fixed diff --git a/js/base.js b/js/base.js index a14070e..00b4d6f 100644 --- a/js/base.js +++ b/js/base.js @@ -1,4 +1,4 @@ -import { API as BaseAPI, mix, load, conf } from "yonius"; +import { API as BaseAPI, mix, load, conf, verify } from "yonius"; import { InvoiceAPI } from "./invoice"; import { SequenceAPI } from "./sequence"; @@ -28,4 +28,39 @@ export class API extends mix(BaseAPI).with(InvoiceAPI, SequenceAPI, TaxAPI) { options.params = options.params !== undefined ? options.params : {}; options.params.api_key = this.apiKey; } + + async _handleResponse(response, errorMessage = "Problem in request") { + const result = await this._getResult(response); + const errors = result.errors ? JSON.stringify(result.errors) : null; + verify(!errors, errors, response.status || 500); + verify(response.ok, errorMessage, response.status || 500); + return result; + } + + /** + * Obtains the response object from the provided response making sure that the + * content type is respected when doing so. + * + * @param {Response} response The HTTP response resulting from the request + * made by the API client + * @returns {Object|String|Blob} The parsed result value for the provided + * response object taking into account the content type of it. + */ + async _getResult(response) { + let result = null; + if ( + response.headers.get("content-type") && + response.headers.get("content-type").toLowerCase().startsWith("application/json") + ) { + result = await response.json(); + } else if ( + response.headers.get("content-type") && + response.headers.get("content-type").toLowerCase().startsWith("text/") + ) { + result = await response.text(); + } else { + result = await response.blob(); + } + return result; + } }