node-telegram-api/build/functions/fetch.js

74 lines
1.8 KiB
JavaScript
Raw Normal View History

2015-07-05 13:36:27 +00:00
'use strict';
Object.defineProperty(exports, "__esModule", {
2015-07-05 13:36:27 +00:00
value: true
});
exports.default = fetch;
2015-07-05 13:36:27 +00:00
exports.getBody = getBody;
var _unirest = require('unirest');
2015-07-05 13:36:27 +00:00
var _unirest2 = _interopRequireDefault(_unirest);
2015-07-05 13:36:27 +00:00
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2015-07-05 13:36:27 +00:00
function fetch(path) {
var data = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
2015-07-05 13:36:27 +00:00
return new Promise(function (resolve, reject) {
var files = {};
2015-07-05 13:36:27 +00:00
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Object.keys(data)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var key = _step.value;
if (data[key].file) {
files[key] = data[key].file;
delete data[key];
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
2015-07-05 13:36:27 +00:00
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
_unirest2.default.post('https://api.telegram.org/bot' + path).field(data).attach(files).end(function (response) {
2015-07-27 05:38:52 +00:00
if (response.statusType === 4 || response.statusType === 5 || !response.body || !response.body.ok) {
reject(response);
} else {
resolve(response.body);
2015-07-05 13:36:27 +00:00
}
});
});
}
function getBody(stream) {
var data = '';
return new Promise(function (resolve, reject) {
stream.on('data', function (chunk) {
data += chunk;
});
stream.on('end', function () {
resolve(data);
});
stream.on('error', reject);
});
}