Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: better result errors #15

Merged
merged 1 commit into from
Oct 4, 2023
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
37 changes: 36 additions & 1 deletion js/base.js
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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;
}
}