@bigmi/core
Version:
TypeScript library for Bitcoin apps.
80 lines • 3.18 kB
JavaScript
import { HttpRequestError, TimeoutError } from '../errors/request.js';
import { stringify } from '../utils/stringify.js';
import { withTimeout } from '../utils/withTimeout.js';
export 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 withTimeout(async ({ signal }) => {
const init = {
...fetchOptions,
body: body ? 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 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 HttpRequestError({
body,
details: stringify(data.error) || response.statusText,
headers: response.headers,
status: response.status,
url,
});
}
return data;
}
catch (err) {
if (err instanceof HttpRequestError) {
throw err;
}
if (err instanceof TimeoutError) {
throw err;
}
throw new HttpRequestError({
body,
cause: err,
url,
});
}
},
};
}
//# sourceMappingURL=getHttpRpcClient.js.map