UNPKG

alwaysai

Version:

The alwaysAI command-line interface (CLI)

57 lines 2.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fetchFilestream = exports.downloadJson = exports.fetchWithTimeout = exports.throwIfNotOk = void 0; const coded_error_1 = require("@carnesen/coded-error"); const logger_1 = require("./logger"); const node_stream_1 = require("node:stream"); async function throwIfNotOk(response) { if (!response.ok) { logger_1.logger.error(`Status: ${response.status}, ${response.statusText}`); const message = `Server responded ${response.status} ("${response.statusText}")`; const code = response.status; throw new coded_error_1.CodedError(message, code); } } exports.throwIfNotOk = throwIfNotOk; async function fetchWithTimeout(url, options = {}, timeout = 6000) { const controller = new AbortController(); const id = setTimeout(() => controller.abort(), timeout); try { const response = await fetch(url, Object.assign(Object.assign({}, options), { signal: controller.signal })); clearTimeout(id); await throwIfNotOk(response); if (response.body === null) { throw new Error(`Body empty for query ${url}`); } // Typescript matches the wrong type to body (DOM) so cast body to desired type return response; } catch (error) { clearTimeout(id); if (error.name === 'AbortError') { throw new Error('Request timed out'); } else { throw error; } } } exports.fetchWithTimeout = fetchWithTimeout; async function downloadJson(url) { const options = { method: 'Get' }; const response = await fetchWithTimeout(url, options); await throwIfNotOk(response); return response.json(); } exports.downloadJson = downloadJson; async function fetchFilestream(url, options = {}) { const response = await fetchWithTimeout(url, Object.assign({}, options)); await throwIfNotOk(response); if (response.body === null) { throw new Error(`Body empty for query ${url}`); } // Typescript matches the wrong type to body (DOM) so cast body to desired type return node_stream_1.Readable.fromWeb(response.body); } exports.fetchFilestream = fetchFilestream; //# sourceMappingURL=fetch.js.map