@gam-test/fetch-wrapper
Version:
A simple fetch wrapper for better error handling and less response context
56 lines (53 loc) • 1.69 kB
JavaScript
Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _UnexpectedResponseExceptionjs = require('./exceptions/UnexpectedResponseException.js');
class HttpClient {
constructor({ url }) {
this.url = url;
}
async request(config) {
const response = await this.connect(config);
if (!("bodyParser" in config)) {
return {
status: response.status,
headers: response.headers
};
}
if (!config.bodyParser) {
return {
status: response.status,
headers: response.headers
};
}
try {
const body = await config.bodyParser(response);
return {
status: response.status,
headers: response.headers,
body
};
} catch (error) {
if (!(error instanceof Error)) {
throw error;
}
const content = await response.text().catch(async () => {
if (!response.body) {
return "No response body.";
}
const bodyReader = response.body.getReader();
const rawBody = await bodyReader.read().catch(() => {
});
if (!rawBody) {
return "Error getting response content";
}
const decoder = new TextDecoder();
return decoder.decode(rawBody.value);
});
throw new (0, _UnexpectedResponseExceptionjs.UnexpectedResponseException)({
url: this.url,
content: _nullishCoalesce(content, () => ( "Error getting response content")),
cause: error
});
}
}
}
exports.HttpClient = HttpClient;
//# sourceMappingURL=HttpClient.js.map
;