@bigmi/core
Version:
TypeScript library for Bitcoin apps.
83 lines • 3.42 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getHttpRpcClient = getHttpRpcClient;
const request_js_1 = require("../errors/request.js");
const stringify_js_1 = require("../utils/stringify.js");
const withTimeout_js_1 = require("../utils/withTimeout.js");
function getHttpRpcClient(url, options = {}) {
return {
async request(params) {
const { body, onRequest = options.onRequest, onResponse = options.onResponse, timeout = options.timeout ?? 10000, } = params;
const fetchOptions = {
...(options.fetchOptions ?? {}),
...(params.fetchOptions ?? {}),
};
const { headers, method, signal: signal_ } = fetchOptions;
try {
const response = await (0, withTimeout_js_1.withTimeout)(async ({ signal }) => {
const init = {
...fetchOptions,
body: body ? (0, stringify_js_1.stringify)(body) : undefined,
headers: {
...(method !== 'GET'
? { 'Content-Type': 'application/json' }
: undefined),
...headers,
},
method: method || 'POST',
signal: signal_ || (timeout > 0 ? signal : null),
};
const request = new Request(params.url ?? url, init);
if (onRequest) {
await onRequest(request, init);
}
const response = await fetch(params.url ?? url, init);
return response;
}, {
errorInstance: new request_js_1.TimeoutError({
body: body ?? {},
url: params.url ?? url,
timeout,
}),
timeout,
signal: true,
});
if (onResponse) {
await onResponse(response);
}
let data;
if (response.headers.get('Content-Type')?.startsWith('application/json')) {
data = await response.json();
}
else {
data = await response.text();
data = JSON.parse(data || '{}');
}
if (!response.ok) {
throw new request_js_1.HttpRequestError({
body,
details: (0, stringify_js_1.stringify)(data.error) || response.statusText,
headers: response.headers,
status: response.status,
url,
});
}
return data;
}
catch (err) {
if (err instanceof request_js_1.HttpRequestError) {
throw err;
}
if (err instanceof request_js_1.TimeoutError) {
throw err;
}
throw new request_js_1.HttpRequestError({
body,
cause: err,
url,
});
}
},
};
}
//# sourceMappingURL=getHttpRpcClient.js.map