From ff26b54cdc5b018bfa731331fc47fc91ae4f22b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Conde?= <16060539+joao-conde@users.noreply.github.com> Date: Wed, 4 Oct 2023 17:35:52 +0100 Subject: [PATCH] feat: better result errors --- CHANGELOG.md | 1 + js/base.js | 37 ++++++++++++++++++++++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) 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; + } }