UNPKG

bitcore-wallet-client

Version:
249 lines 9.93 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Request = void 0; const superagent_1 = __importDefault(require("superagent")); const util_1 = __importDefault(require("util")); const common_1 = require("./common"); const errors_1 = require("./errors"); const log_1 = __importDefault(require("./log")); const Package = require('../../package.json'); ; class Request { constructor(url, opts) { this.baseUrl = url; this.r = opts.r || superagent_1.default; this.supportStaffWalletId = opts.supportStaffWalletId; this.session = null; this.credentials = null; } setCredentials(credentials) { this.credentials = credentials; } getHeaders(method, url, args, useSession) { var headers = { 'x-client-version': 'bwc-' + Package.version }; if (this.supportStaffWalletId) { headers['x-wallet-id'] = this.supportStaffWalletId; } this._populateAuth(headers, { method, url, args }, useSession); return headers; } _populateAuth(headers, signingParams, useSession) { if (this.credentials) { headers['x-identity'] = this.credentials.copayerId; if (useSession && this.session) { headers['x-session'] = this.session; } else { const { _requestPrivKey } = signingParams, params = __rest(signingParams, ["_requestPrivKey"]); const privKey = _requestPrivKey || this.credentials.requestPrivKey; if (privKey) { headers['x-signature'] = this._signRequest(Object.assign(Object.assign({}, params), { privKey })); } } } } _signRequest({ method, url, args, privKey }) { var message = `${method.toLowerCase()}|${url}|${JSON.stringify(args)}`; return common_1.Utils.signMessage(message, privKey); } doRequest(method, url, args, useSession, cb) { return __awaiter(this, void 0, void 0, function* () { var headers = this.getHeaders(method, url, args, useSession); var r = this.r[method](this.baseUrl + url); r.accept('json'); for (const [k, v] of Object.entries(headers)) { if (v) r.set(k, v); } if (args) { if (method == 'post' || method == 'put') { r.send(args); } else { r.query(args); } } r.timeout(this.timeout); try { const retval = yield new Promise((resolve, reject) => { r.end((err, res) => { if (!res) { return reject(new errors_1.Errors.CONNECTION_ERROR()); } if (res.body) log_1.default.debug(util_1.default.inspect(res.body, { depth: 10 })); if (res.status !== 200) { if (res.status === 503) return reject(new errors_1.Errors.MAINTENANCE_ERROR()); if (res.status === 404) return reject(new errors_1.Errors.NOT_FOUND()); if (res.status === 413) return reject(new errors_1.Errors.PAYLOAD_TOO_LARGE()); if (!res.status) return reject(new errors_1.Errors.CONNECTION_ERROR()); log_1.default.error('HTTP Error:' + res.status); if (!res.body || !Object.keys(res.body).length) return reject(new Error(res.status + `${(err === null || err === void 0 ? void 0 : err.message) ? ': ' + err.message : ''}`)); return reject(Request._parseError(res.body)); } if (res.body === '{"error":"read ECONNRESET"}') return reject(new errors_1.Errors.ECONNRESET_ERROR(JSON.parse(res.body))); return resolve({ body: res.body, header: res.header }); }); }); if (cb) return cb(null, retval.body, retval.header); return retval; } catch (err) { if (cb) return cb(err); throw err; } }); } static _parseError(body) { var _a; if (!body) return; if (typeof body === 'string') { try { body = JSON.parse(body); } catch (e) { body = { error: body }; } } let ret; if (body.code) { if (errors_1.Errors[body.code]) { ret = new errors_1.Errors[body.code](); if (body.message) ret.message = body.message; if (body.messageData) ret.messageData = body.messageData; } else { ret = new Error(body.code + ': ' + (body.message && typeof body.message === 'object' ? JSON.stringify(body.message) : (_a = body.message) !== null && _a !== void 0 ? _a : 'Unknown BWC request error')); } } else { ret = new Error(body.error || JSON.stringify(body)); } log_1.default.error(ret); return ret; } post(url, body, cb) { return __awaiter(this, void 0, void 0, function* () { body = body || {}; return this.doRequest('post', url, body, false, cb); }); } put(url, body, cb) { return __awaiter(this, void 0, void 0, function* () { body = body || {}; return this.doRequest('put', url, body, false, cb); }); } get(url, cb) { return __awaiter(this, void 0, void 0, function* () { url += url.indexOf('?') > 0 ? '&' : '?'; url += 'r=' + Math.round(Math.random() * 100000); return this.doRequest('get', url, {}, false, cb); }); } delete(url, cb) { return __awaiter(this, void 0, void 0, function* () { return this.doRequest('delete', url, {}, false, cb); }); } getWithLogin(url, cb) { url += url.indexOf('?') > 0 ? '&' : '?'; url += 'r=' + Math.round(Math.random() * 100000); return this.doRequestWithLogin('get', url, {}, cb); } _login(cb) { return __awaiter(this, void 0, void 0, function* () { return this.post('/v1/login', {}, cb); }); } logout(cb) { return __awaiter(this, void 0, void 0, function* () { return this.post('/v1/logout', {}, cb); }); } doRequestWithLogin(method_1, url_1, body_1, cb_1) { return __awaiter(this, arguments, void 0, function* (method, url, body, cb, retry = true) { try { if (!this.session) { yield this.doLogin(); } const result = yield this.doRequest(method, url, body, true); if (cb) return cb(null, result.body, result.header); return result; } catch (err) { if (err instanceof errors_1.Errors.NOT_AUTHORIZED && retry) { this.session = null; return this.doRequestWithLogin(method, url, body, cb, false); } if (!cb) throw err; return cb(err); } }); } doLogin(cb) { return __awaiter(this, void 0, void 0, function* () { try { const s = yield this._login(); if (!(s === null || s === void 0 ? void 0 : s.body)) throw new errors_1.Errors.NOT_AUTHORIZED(); this.session = s.body; if (cb) return cb(); } catch (err) { if (!cb) throw err; return cb(err); } }); } } exports.Request = Request; //# sourceMappingURL=request.js.map