blockbook-client
Version:
Client for interacting with Trezor's blockbook API
56 lines • 2.02 kB
JavaScript
import axios from 'axios';
import { isString } from '@bitaccess/ts-common';
import qs from 'qs';
export const USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36';
function tryParseJson(body) {
try {
return JSON.parse(body);
}
catch (e) {
return body;
}
}
export async function jsonRequest(host, method, path, params, body, options) {
var _a, _b, _c;
if (!host.startsWith('http')) {
host = `https://${host}`;
}
const queryString = params ? qs.stringify(params, { addQueryPrefix: true }) : '';
const uri = `${host}${path}${queryString}`;
const fullOptions = {
url: uri,
method,
data: body,
responseType: 'json',
...options,
headers: {
'user-agent': USER_AGENT,
},
};
try {
let { data } = await axios.request(fullOptions);
if ((_a = data === null || data === void 0 ? void 0 : data.error) === null || _a === void 0 ? void 0 : _a.message) {
throw new Error(data.error.message);
}
return data;
}
catch (e) {
if (axios.isAxiosError(e)) {
const body = (_b = e.response) === null || _b === void 0 ? void 0 : _b.data;
if (isString(body === null || body === void 0 ? void 0 : body.error)) {
throw new Error(body.error);
}
else if (isString((_c = body === null || body === void 0 ? void 0 : body.error) === null || _c === void 0 ? void 0 : _c.message)) {
throw new Error(body.error.message);
}
if (e.code === '522') {
e.message = `StatusCodeError: 522 Origin Connection Time-out ${method} ${uri}`;
}
else if (e.code === '504') {
e.message = `StatusCodeError: 504 Gateway Time-out ${method} ${uri}`;
}
}
throw e;
}
}
//# sourceMappingURL=utils.js.map