UNPKG

golos-lib-js

Version:

Golos-js the JavaScript library with API for GOLOS blockchain

92 lines (91 loc) 2.65 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.RPCError = void 0; exports.jsonRpc = jsonRpc; var _debug = _interopRequireDefault(require("debug")); var _config = _interopRequireDefault(require("../../config")); var _base = _interopRequireDefault(require("./base")); var _promisify = require("../../promisify"); var _fetchEx = _interopRequireDefault(require("../../utils/fetchEx")); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } const cbMethods = ['set_block_applied_callback', 'set_pending_transaction_callback', 'set_callback', 'subscribe_to_market']; const debugProtocol = (0, _debug.default)('golos:protocol'); const debugHttp = (0, _debug.default)('golos:http'); class RPCError extends Error { constructor(rpcError, rpcRes) { super(rpcError.message); this.name = 'RPCError'; this.code = rpcError.code; this.data = rpcError.data; this.resid = rpcRes.id; } } exports.RPCError = RPCError; function jsonRpc(uri, _ref) { let { method, id, params } = _ref; const payload = { id, jsonrpc: '2.0', method, params }; let req = { body: JSON.stringify(payload), method: 'post', mode: 'cors', headers: { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, timeout: _config.default.get('node_timeout') }; req.credentials = _config.default.get('credentials'); if (!req.credentials) delete req.credentials; return (0, _fetchEx.default)(uri, req).then(res => { if (!res.ok) { throw new Error(`HTTP ${res.status}: ${res.statusText}`); } return res.json(); }).then(rpcRes => { if (rpcRes.id !== id) { throw new Error(`Invalid response id: ${rpcRes.id}`); } if (rpcRes.error) { throw new RPCError(rpcRes.error, rpcRes); } return rpcRes; }); } class HttpTransport extends _base.default { constructor() { let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(Object.assign({ id: 0 }, options)); } send(api, data, callback) { const id = data.id || this.id++; this.currentP = new Promise((resolve, reject) => { const params = [api, data.method, data.params]; const url = this.getURL(); jsonRpc(url, { method: 'call', id, params }).then(res => { resolve(res.result); }, err => { reject(err); }); }); this.currentP = (0, _promisify.nodeify)(this.currentP, callback); return this.currentP; } } exports.default = HttpTransport;