UNPKG

@gam-test/fetch-wrapper

Version:

A simple fetch wrapper for better error handling and less response context

56 lines 1.45 kB
import { UnexpectedResponseException } from "./exceptions/UnexpectedResponseException.js"; class HttpClient { url; 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 UnexpectedResponseException({ url: this.url, content: content ?? "Error getting response content", cause: error }); } } } export { HttpClient }; //# sourceMappingURL=HttpClient.js.map