baasic-sdk-nodejs
Version:
NodeJS SDK provides core functionality for building web and mobile applications on [Baasic](http://www.baasic.com/).
81 lines (80 loc) • 2.74 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var http = require("http");
var https = require("https");
var HttpClient = (function () {
function HttpClient() {
}
HttpClient.prototype.createPromise = function (deferFn) {
return new Promise(deferFn);
};
HttpClient.prototype.request = function (request) {
return this.createPromise(function (resolve, reject) {
var headers = Object.assign({}, request.headers);
var postData;
if (request.data) {
var dataType = headers['Content-Type'];
if (dataType.indexOf('application/json') !== -1) {
postData = JSON.stringify(request.data);
}
else {
postData = request.data;
}
}
if (postData) {
headers['Content-Length'] = Buffer.byteLength(postData);
}
var url = request.url;
var path = url.pathname;
if (url.search) {
path += url.search;
}
var client;
if (url.protocol.startsWith('https')) {
client = https;
}
else {
client = http;
}
var req = client.request({
hostname: url.hostname,
port: url.port ? parseInt(url.port) : undefined,
path: path,
method: request.method,
headers: headers
}, function (res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
var response = {
request: request,
headers: res.headers,
statusCode: res.statusCode,
statusText: res.statusMessage,
data: body ? JSON.parse(body) : null
};
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(response);
}
else {
reject(response);
}
});
});
req.on('error', function (e) {
reject(e);
});
if (postData) {
req.write(postData);
}
req.end();
});
};
;
return HttpClient;
}());
exports.HttpClient = HttpClient;
;