UNPKG

wehelpjs

Version:

wehelpjs is the JavaScript API Library for the WeYouMe blockchain

93 lines (77 loc) 1.95 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.jsonRpc = jsonRpc; exports.default = void 0; var _crossFetch = _interopRequireDefault(require("cross-fetch")); var _debug = _interopRequireDefault(require("debug")); var _base = _interopRequireDefault(require("./base")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug.default)('wehelpjs:http'); class RPCError extends Error { constructor(rpcError) { super(rpcError.message); this.name = 'RPCError'; this.code = rpcError.code; this.data = rpcError.data; } } function jsonRpc(uri, { method, id, params }) { const payload = { id, jsonrpc: '2.0', method, params }; return (0, _crossFetch.default)(uri, { body: JSON.stringify(payload), method: 'post', mode: 'cors', headers: { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json' } }).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); } return rpcRes.result; }); } class HttpTransport extends _base.default { send(api, data, callback) { if (this.options.useAppbaseApi) { api = 'condenser_api'; } debug('wehelpjs::send', api, data); const id = data.id || this.id++; const params = [api, data.method, data.params]; jsonRpc(this.options.uri, { method: 'call', id, params }).then(res => { if (typeof callback == 'function') { callback(null, res); } }, err => { if (typeof callback == 'function') { callback(err); } }); } } exports.default = HttpTransport;