@onekeyfe/blockchain-libs
Version:
OneKey Blockchain Libs
71 lines • 2.78 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RestfulRequest = void 0;
const buffer_1 = require("buffer");
const cross_fetch_1 = __importDefault(require("cross-fetch"));
const timeout_signal_1 = __importDefault(require("timeout-signal"));
const whatwg_url_1 = require("whatwg-url");
const exceptions_1 = require("./exceptions");
class RestfulRequest {
constructor(baseUrl, headers, timeout = 10000) {
this.baseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
this.timeout = timeout;
this.headers = {};
if (headers) {
Object.assign(this.headers, headers);
}
}
static async handleResponse(response) {
if (!response.ok) {
throw new exceptions_1.ResponseError(`Wrong response<${response.status}>`, response);
}
return response;
}
async get(path, params, headers, timeout) {
headers = this.assembleHeaders(headers);
const url = this.buildUrl(path);
if (typeof params === 'object') {
url.search = new whatwg_url_1.URLSearchParams(params).toString();
}
const response = await (0, cross_fetch_1.default)(url.toString(), {
headers,
signal: (0, timeout_signal_1.default)(timeout || this.timeout),
});
return RestfulRequest.handleResponse(response);
}
async post(path, data, json = false, headers, timeout) {
headers = this.assembleHeaders(headers);
if (json) {
headers['Content-Type'] = 'application/json';
}
const url = this.buildUrl(path);
const body = headers['Content-Type'] === 'application/x-binary'
? buffer_1.Buffer.from(data, 'hex')
: typeof data === 'object'
? json
? JSON.stringify(data)
: new whatwg_url_1.URLSearchParams(data).toString()
: data;
const response = await (0, cross_fetch_1.default)(url.toString(), {
method: 'POST',
headers,
body,
signal: (0, timeout_signal_1.default)(timeout || this.timeout),
});
return RestfulRequest.handleResponse(response);
}
buildUrl(path) {
path = path.startsWith('/') ? path : `/${path}`;
const url = `${this.baseUrl}${path}`;
return new whatwg_url_1.URL(url);
}
assembleHeaders(headers) {
headers = headers || {};
return Object.assign(Object.assign({}, this.headers), headers);
}
}
exports.RestfulRequest = RestfulRequest;
//# sourceMappingURL=restful.js.map