@machinemode/cryptopia
Version:
Node wrapper for Cryptopia's CLient API
89 lines • 3.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var https = require("https");
var Amx_1 = require("./Amx");
var ApiResponse_1 = require("./ApiResponse");
var HttpsClient = (function () {
function HttpsClient(hostname, key, secret) {
this.hostname = hostname;
this.key = key;
this.secret = secret;
if (this.key && this.secret) {
this.amx = new Amx_1.default("https://" + this.host, this.key, this.secret);
}
}
Object.defineProperty(HttpsClient.prototype, "host", {
get: function () {
return this.hostname;
},
enumerable: true,
configurable: true
});
HttpsClient.prototype.get = function (path) {
var _this = this;
var options = {
hostname: this.hostname,
ca: this.ca,
path: path,
method: 'GET',
headers: { 'Accept': 'application/json' }
};
return new Promise(function (resolve, reject) {
_this.request(options, undefined, resolve, reject)
.on('error', function (error) { return reject(error); })
.end();
});
};
HttpsClient.prototype.post = function (path, body) {
var _this = this;
if (body === void 0) { body = {}; }
var options = {
hostname: this.hostname,
ca: this.ca,
path: path,
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': this.amx.makeToken(path, body),
'Content-Type': 'application/json'
}
};
return new Promise(function (resolve, reject) {
_this.request(options, body, resolve, reject)
.on('error', function (error) { return reject(error); })
.end();
});
};
HttpsClient.prototype.request = function (options, requestBody, resolve, reject) {
var _this = this;
var request = https.request(options, function (res) { return _this.onResponse(res, resolve, reject); });
if (requestBody) {
request.write(JSON.stringify(requestBody));
}
return request;
};
HttpsClient.prototype.onResponse = function (res, resolve, reject) {
var responseBody = '';
res.on('data', function (data) {
if (data instanceof Buffer) {
responseBody += data.toString();
}
else {
responseBody += data;
}
});
res.on('end', function () {
var response = new ApiResponse_1.default(res.statusCode || 0, responseBody);
if (response.ok) {
resolve(response);
}
else {
var reason = "Server responded with " + response.status + "\n" + response.body.toString();
reject(new Error(reason));
}
});
};
return HttpsClient;
}());
exports.default = HttpsClient;
//# sourceMappingURL=HttpsClient.js.map